import { NextRequest, NextResponse } from "next/server"
import { login } from "@/lib/auth"
import { rateLimit } from "@/lib/rate-limit"

export async function POST(request: NextRequest) {
  const ip = request.headers.get("x-forwarded-for") || "unknown"
  if (!rateLimit(ip, 5, 60_000)) {
    return NextResponse.json({ error: "For mange forsøg. Prøv igen om lidt." }, { status: 429 })
  }

  try {
    const { email, password } = await request.json()

    if (!email || !password) {
      return NextResponse.json({ error: "Email og adgangskode er påkrævet" }, { status: 400 })
    }

    const result = await login(email, password)

    if (!result.success) {
      return NextResponse.json({ error: result.error }, { status: 401 })
    }

    return NextResponse.json({ success: true })
  } catch {
    return NextResponse.json({ error: "Der opstod en fejl" }, { status: 500 })
  }
}
