import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { connectDB } from "@/lib/db";
import { Client } from "@/models/Client";
import { getPendingPasswordChangePayload, destroyPendingPasswordChangeToken, createSession, hashPassword } from "@/lib/auth";
import { corsHeaders, corsPreflight } from "@/lib/teamApiCors";

export async function OPTIONS(request: NextRequest) {
  return corsPreflight(request);
}

export async function POST(request: NextRequest) {
  const headers = corsHeaders(request);
  const pending = await getPendingPasswordChangePayload();
  if (!pending) return NextResponse.json({ error: "Die Anmeldung ist abgelaufen — bitte erneut einloggen." }, { status: 401, headers });

  const body = await request.json().catch(() => null);
  const password = typeof body?.password === "string" ? body.password : "";
  const confirmPassword = typeof body?.confirmPassword === "string" ? body.confirmPassword : "";

  if (password.length < 8) {
    return NextResponse.json({ error: "Passwort muss mindestens 8 Zeichen haben." }, { status: 400, headers });
  }
  if (password !== confirmPassword) {
    return NextResponse.json({ error: "Die Passwörter stimmen nicht überein." }, { status: 400, headers });
  }

  await connectDB();
  const client = await Client.findById(pending.clientId);
  if (!client) {
    await destroyPendingPasswordChangeToken();
    return NextResponse.json({ error: "Die Anmeldung ist abgelaufen — bitte erneut einloggen." }, { status: 401, headers });
  }

  client.passwordHash = await hashPassword(password);
  client.mustChangePassword = false;
  await client.save();

  await destroyPendingPasswordChangeToken();
  await createSession(String(client._id), true);
  return NextResponse.json({ ok: true, name: client.name }, { headers });
}
