"use server";

import { prisma } from "@/core/db/prisma";
import { createSession } from "@/core/security/session";
import { loginSchema, LoginFormValues } from "./login-schema";
import { compare } from "bcryptjs";
import { getLocale } from "next-intl/server";

export type ActionResponse = {
  success: boolean;
  message?: string;
};

export async function loginAction(data: LoginFormValues): Promise<ActionResponse> {
  try {
    // 1. Validate Input
    const validatedData = loginSchema.safeParse(data);
    if (!validatedData.success) {
      return { success: false, message: "Invalid credentials format" };
    }

    const { email, password } = validatedData.data;

    // 2. Find User
    const user = await prisma.user.findUnique({
      where: { email },
    });

    if (!user) {
      return { success: false, message: "Invalid email or password" };
    }

    // 3. Verify Password
    const passwordMatch = await compare(password, user.passwordHash);

    if (!passwordMatch) {
      return { success: false, message: "Invalid email or password" };
    }

    // 4. Create Session Cookie
    await createSession(user.id, user.email);

    return { success: true };
  } catch (error) {
    console.error("Login failed:", error);
    return { success: false, message: "An unexpected error occurred" };
  }
}
