import { NextResponse } from "next/server";
import { createSessionToken, getAdminCredentials, getSessionCookieName } from "@/lib/auth";

type LoginPayload = {
  email?: string;
  password?: string;
};

export async function POST(request: Request) {
  try {
    const body = (await request.json()) as LoginPayload;
    const email = body.email?.trim().toLowerCase() || "";
    const password = body.password?.trim() || "";

    const admin = getAdminCredentials();

    if (email !== admin.email.toLowerCase() || password !== admin.password) {
      return NextResponse.json({ error: "Неверный email или пароль" }, { status: 401 });
    }

    const token = await createSessionToken(email);
    const response = NextResponse.json({ success: true });

    response.cookies.set({
      name: getSessionCookieName(),
      value: token,
      httpOnly: true,
      secure: true,
      sameSite: "lax",
      path: "/",
      maxAge: 60 * 60 * 24 * 7,
    });

    return response;
  } catch {
    return NextResponse.json({ error: "Ошибка авторизации" }, { status: 500 });
  }
}