"use server";
import { signIn } from '@/auth';
import { DEFAULT_LOGIN_REDIRECT } from '@/routes';
import { AuthError } from 'next-auth';
import { isRedirectError } from "next/dist/client/components/redirect";

export const login = async (values: any) => {
    try {
        const auth = await signIn("credentials", {
            username: values.username,
            password: values.password,
            redirectTo: DEFAULT_LOGIN_REDIRECT,
            redirect: true, 
        });
        
        return auth;

    } catch (error) {
        if (error instanceof Error) {

            if (isRedirectError(error)) {
                throw error;
            }
            const { type, cause } = error as AuthError;
            switch (type) {
                case "CredentialsSignin":
                    return "Invalid credentials.";
                case "CallbackRouteError":
                    return cause?.err?.toString();
                default:
                    return "Something went wrong.";
            }
        }

        throw error;
    }
}