import { NextResponse } from "next/server";
import { z } from "zod";
import { verifyPassword } from "@/lib/auth/password";
import { signSession } from "@/lib/auth/session";
import { getSetting, SETTINGS } from "@/lib/settings";

const Body = z.object({ password: z.string().min(1) });

export async function POST(req: Request) {
  let parsed;
  try {
    parsed = Body.safeParse(await req.json());
  } catch {
    return NextResponse.json({ error: "invalid_json" }, { status: 400 });
  }
  if (!parsed.success) {
    return NextResponse.json({ error: "missing_password" }, { status: 400 });
  }

  const hash = await getSetting(SETTINGS.PASSWORD_HASH);
  if (!hash) {
    return NextResponse.json({ error: "no_password_set" }, { status: 500 });
  }

  const ok = await verifyPassword(parsed.data.password, hash);
  if (!ok) {
    return NextResponse.json({ error: "invalid_credentials" }, { status: 401 });
  }

  const token = await signSession({ sub: "admin" });
  const res = NextResponse.json({ ok: true });
  res.headers.set(
    "Set-Cookie",
    `pm_session=${token}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${60 * 60 * 24 * 7}`,
  );
  return res;
}
