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";
import { _n } from "@/src/exports/client-exports";
import setupDeploymentUser from "@/src/functions/deployment-users/setup-deployment-user";

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 || !user.super_admin) {
            return res.json({
                success: false,
                msg: "Unauthorized",
            });
        }

        const { new_user, user_id } = req.body as APIReqObject;

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

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

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

        const update: NSQLITE_TURBOCI_ADMIN_USERS = {
            first_name,
            last_name,
            email,
            image,
            username,
        };

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

        await setupDeploymentUser({ user_id: _n(user_id) });

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