import { NextRequest, NextResponse } from "next/server"
import { getAllQuotes, updateQuoteStatus, type QuoteStatus } from "@/lib/db"
import { getCurrentUser } from "@/lib/auth"

export async function GET() {
  try {
    const user = await getCurrentUser()
    if (!user) {
      return NextResponse.json({ error: "Ikke autoriseret" }, { status: 401 })
    }

    const quotes = getAllQuotes()
    return NextResponse.json({ quotes })
  } catch (error) {
    console.error("Get quotes error:", error)
    return NextResponse.json({ error: "Der opstod en fejl" }, { status: 500 })
  }
}

export async function PATCH(request: NextRequest) {
  try {
    const user = await getCurrentUser()
    if (!user) {
      return NextResponse.json({ error: "Ikke autoriseret" }, { status: 401 })
    }

    const { id, status } = await request.json()

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

    const validStatuses: QuoteStatus[] = ["new", "contacted", "accepted", "rejected"]
    if (!validStatuses.includes(status)) {
      return NextResponse.json({ error: "Ugyldig status" }, { status: 400 })
    }

    const success = updateQuoteStatus(id, status)
    if (!success) {
      return NextResponse.json({ error: "Tilbud ikke fundet" }, { status: 404 })
    }

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