import { NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import {
  verifyPassword,
  createSession,
  setSessionCookie,
  writeAuditLog,
  extractRequestMeta,
} from "@/lib/auth";
import { loginLimiter, getLimiterKey, tooManyRequests } from "@/lib/ratelimit";

export async function POST(req: Request) {
  // ── Rate limiting ──────────────────────────────────────────────────────────
  const limitKey = getLimiterKey(req, "login");
  const limit    = loginLimiter.check(limitKey);
  if (!limit.allowed) return tooManyRequests(limit.resetIn);

  try {
    const body = await req.json().catch(() => null);
    if (!body || typeof body !== "object") {
      return NextResponse.json({ error: "Invalid request body" }, { status: 400 });
    }

    const { email, password } = body as Record<string, unknown>;

    if (typeof email !== "string" || typeof password !== "string" || !email || !password) {
      return NextResponse.json({ error: "Email and password are required" }, { status: 400 });
    }

    // Normalize email
    const normalizedEmail = email.trim().toLowerCase();

    // ── Find clinic ──────────────────────────────────────────────────────────
    const clinic = await prisma.clinic.findUnique({
      where: { email: normalizedEmail },
      select: { id: true, email: true, passwordHash: true },
    });

    // Timing-safe: always hash compare even if clinic not found
    const dummyHash = "$2a$12$K8BpgKB4Y5lC6PGfMkqv0e1LJK8m1OHfZhc5qAEHq8MPvxZrAFKMO";
    const hashToCheck = clinic?.passwordHash ?? dummyHash;

    const valid = await verifyPassword(password, hashToCheck);

    if (!clinic || !valid || !clinic.passwordHash) {
      // Don't reveal which field was wrong
      return NextResponse.json({ error: "Invalid email or password" }, { status: 401 });
    }

    // ── Create DB session ────────────────────────────────────────────────────
    const meta  = extractRequestMeta(req);
    const token = await createSession(clinic.id, meta);
    await setSessionCookie(token);

    // ── Audit log ────────────────────────────────────────────────────────────
    await writeAuditLog({
      clinicId: clinic.id,
      action:   "login.email",
      actor:    clinic.email,
      request:  req,
    });

    // Reset rate limiter on successful login
    loginLimiter.reset(limitKey);

    return NextResponse.json({ success: true, clinicId: clinic.id });
  } catch (error) {
    console.error("[Login]", error);
    return NextResponse.json({ error: "Login failed" }, { status: 500 });
  }
}
