import { NextResponse } from "next/server"
import ExcelJS from "exceljs"
import { createClient } from "@/lib/supabase/server"

export async function GET() {
  const supabase = await createClient()

  // ── Fetch resource types ───────────────────────────────────────────────────
  const { data: resourceTypes } = await supabase
    .from("resource_types")
    .select("name")
    .eq("is_active", true)
    .order("name")

  const typeNames = (resourceTypes ?? []).map((rt) => rt.name)

  // ── Fetch locations — leaf nodes only ──────────────────────────────────────
  const { data: locations } = await (supabase.from("locations" as any) as any)
    .select("id, parent_id, value, path")
    .eq("is_active", true)
    .order("value")

  const allLocations = (locations ?? []) as Array<{
    id: string
    parent_id: string | null
    value: string
    path: string[]
  }>

  const parentIds = new Set(
    allLocations.filter((l) => l.parent_id).map((l) => l.parent_id!),
  )

  const leafLocations = allLocations
    .filter((l) => !parentIds.has(l.id))
    .map((l) => (l.path ?? []).join(" > "))
    .filter(Boolean)

  // ── Build workbook ─────────────────────────────────────────────────────────
  const wb = new ExcelJS.Workbook()
  const ws = wb.addWorksheet("Recursos")

  // ── Headers ────────────────────────────────────────────────────────────────
  ws.columns = [
    { header: "Nombre", key: "nombre", width: 28 },
    { header: "Tipo de recurso", key: "tipo", width: 24 },
    { header: "Ubicación", key: "ubicacion", width: 28 },
    { header: "Capacidad", key: "capacidad", width: 16 },
    { header: "Detalle ubicación", key: "detalle", width: 24 },
    { header: "Descripción", key: "descripcion", width: 28 },
    { header: "Amenidades", key: "amenidades", width: 24 },
    { header: "Imagen URL", key: "imagen", width: 24 },
    { header: "Activo", key: "activo", width: 12 },
  ]

  // ── Data validations ───────────────────────────────────────────────────────
  // Column B — Tipo de recurso
  if (typeNames.length > 0) {
    ws.dataValidations.add("B2:B1000", {
      type: "list",
      allowBlank: true,
      formulae: [`"${typeNames.join(",")}"`],
      showErrorMessage: true,
      errorTitle: "Tipo inválido",
      error: "Seleccioná un tipo de recurso válido de la lista.",
    })
  }

  // Column C — Ubicación
  if (leafLocations.length > 0) {
    ws.dataValidations.add("C2:C1000", {
      type: "list",
      allowBlank: true,
      formulae: [`"${leafLocations.join(",")}"`],
      showErrorMessage: true,
      errorTitle: "Ubicación inválida",
      error: "Seleccioná una ubicación válida de la lista.",
    })
  }

  // Column I — Activo
  ws.dataValidations.add("I2:I1000", {
    type: "list",
    allowBlank: true,
    formulae: ['"Sí,No"'],
    showErrorMessage: true,
  })

  // ── Serialize and return ───────────────────────────────────────────────────
  const buf = await wb.xlsx.writeBuffer()

  return new NextResponse(buf, {
    status: 200,
    headers: {
      "Content-Type":
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      "Content-Disposition": 'attachment; filename="plantilla_recursos.xlsx"',
    },
  })
}
