import loginUser from "@/src/functions/auth/login-user";
import { NSQLITE_TURBOCI_ADMIN_USERS } from "@/src/db/types";
import userAuth from "@/src/utils/user-auth";
import NSQLite from "@moduletrace/nsqlite";
import { APIResponseObject } from "@moduletrace/datasquirel/dist/package-shared/types";
import type { NextApiRequest, NextApiResponse } from "next";
import { APIReqObject } from "@/src/types";

export default async function handler(
    req: NextApiRequest,
    res: NextApiResponse<APIResponseObject>,
) {
    try {
        if (req.method !== "POST") {
            return res.json({
                success: false,
                msg: "Wrong Method",
            });
        }

        const { singleRes: user } = await userAuth({ req });

        if (!user?.id) {
            return res.json({
                success: false,
                msg: "Unauthorized",
            });
        }

        const { new_user } = req.body as APIReqObject;

        if (!new_user) {
            throw new Error(`No User Form Sent.`);
        }

        const { first_name, last_name, email, image } = new_user;

        if (!first_name?.match(/./)) {
            return res.json({ success: false, msg: "First name is required" });
        }

        const update: NSQLITE_TURBOCI_ADMIN_USERS = {};
        if (first_name) update.first_name = first_name;
        if (last_name !== undefined) update.last_name = last_name;
        if (email) update.email = email;
        if (image !== undefined) update.image = image;

        await NSQLite.update({
            table: "users",
            targetId: user.id,
            data: update,
        });

        const updated = await loginUser({
            res,
            user_id: user.id,
            req,
        });

        return res.json(updated);
    } catch (error: any) {
        return res.json({ success: false, msg: error.message });
    }
}
