import {
  ADMIN_SESSION_COOKIE,
  createAdminSessionToken,
} from "@/lib/auth";
import { NextResponse } from "next/server";

export async function POST(req: Request) {
  try {
    const body = await req.json();
    const password = String(body.password ?? "");
    const expected =
      process.env.ADMIN_PASSWORD ?? process.env.ADMIN_PASS ?? "admin";

    if (!password || password !== expected) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const token = await createAdminSessionToken();
    const res = NextResponse.json({ ok: true });
    res.cookies.set(ADMIN_SESSION_COOKIE, token, {
      httpOnly: true,
      sameSite: "lax",
      secure: process.env.NODE_ENV === "production",
      path: "/",
      maxAge: 60 * 60 * 24 * 7,
    });
    return res;
  } catch {
    return NextResponse.json({ error: "Bad request" }, { status: 400 });
  }
}
