"use server";
import { headers } from "next/headers";
import { signIn } from "@/lib/auth/auth";
import { AuthError } from "next-auth";
import { ipFromHeaders, rateLimit } from "@/lib/rate-limit";

export type LoginState = { ok: boolean; message?: string };

export async function loginAction(_prev: LoginState, formData: FormData): Promise<LoginState> {
  const ip = ipFromHeaders(await headers());
  const limit = rateLimit({
    key: `login:${ip}`,
    max: 10,
    windowMs: 15 * 60 * 1000,
  });
  if (!limit.ok) {
    return { ok: false, message: "Too many sign-in attempts. Please try again later." };
  }

  try {
    await signIn("credentials", {
      email: formData.get("email"),
      password: formData.get("password"),
      redirectTo: "/account",
    });
    return { ok: true };
  } catch (e) {
    if (e instanceof AuthError) {
      return { ok: false, message: "Email or password is incorrect." };
    }
    throw e;
  }
}
