"use server";
import { loginApi, registerApi, userInfoApi } from "@/api/login";
import { getTranslations } from "next-intl/server";
import { cookies } from "next/headers";

export async function loginAction(formData: FormData) {
    const userPhone = formData.get("userPhone") as string;
    const pwd = formData.get("pwd") as string;

    const t = await getTranslations("code");

    try {
        const response = await loginApi({ user_phone: userPhone, pwd });
        const { data } = response;
        if (response.data.token) {
            cookies().set("Token", response.data.token as string);
        }
        if (!Array.isArray(data)) {
            const userInfo = await userInfoApi();
            return {
                success: true,
                user: userInfo.data,
                token: response.data.token,
            };
        }
        return {
            success: false,
            message: t(`${response.code}`),
        };
    } catch (error: any) {
        return {
            success: false,
            message: t(`${error.code}`) || "",
        };
    }
}

export async function registerAction(formData: FormData) {
    const userPhone = formData.get("userPhone") as string;
    const pwd = formData.get("pwd") as string;
    const referrer_code = formData.get("referrer_code") as string;
    const t = await getTranslations("code");
    try {
        const response = await registerApi({ user_phone: userPhone, pwd, referrer_code });
        return {
            success: true,
            message: t(`${response.code}`) || "",
        };
    } catch (error: any) {
        return {
            success: false,
            message: t(`${error.code}`) || "",
        };
    }
}
