import { NextResponse } from "next/server"
import { sql } from "@/lib/db"

export async function GET() {
  try {
    const reports = await sql`
      SELECT * FROM generated_reports ORDER BY created_at DESC LIMIT 20
    `
    return NextResponse.json(reports)
  } catch (error) {
    console.error("Error fetching reports:", error)
    return NextResponse.json([])
  }
}

export async function POST(request: Request) {
  try {
    const body = await request.json()
    const { name, type, start_date, end_date, format } = body

    const result = await sql`
      INSERT INTO generated_reports (name, type, start_date, end_date, format, status)
      VALUES (${name}, ${type}, ${start_date}, ${end_date}, ${format}, 'processing')
      RETURNING *
    `
    return NextResponse.json(result[0])
  } catch (error) {
    console.error("Error creating report:", error)
    return NextResponse.json({ error: "Failed to create report" }, { status: 500 })
  }
}
