import userAuth from "@/src/utils/user-auth";
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 deleteDeploymentUser from "@/src/functions/deployment-users/delete-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 { user_id } = req.body as APIReqObject;

        if (_n(user_id) == user.id) {
            throw new Error(`Can't delete root user!`);
        }

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

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