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

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

        const { email, username, password } = req.body as APIReqObject;

        if (typeof password !== "string" || !password?.match(/./)) {
            throw new Error(`Password is required!`);
        }

        const logged_in_user = await loginUser({
            res,
            email_or_username: email || username,
            password,
            req,
        });

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