import { NextResponse } from "next/server"

const DEFAULT_ALLOWED_ORIGINS = [
  process.env.NEXT_PUBLIC_APP_URL ?? null,
  "https://tickets.esdrasrenan.com.br",
  "http://localhost:1420",
  "http://localhost:3000",
  "tauri://localhost",
].filter((value): value is string => Boolean(value))

export function resolveCorsOrigin(requestOrigin: string | null): string {
  if (!requestOrigin) return "*"
  const allowed = new Set(DEFAULT_ALLOWED_ORIGINS)
  if (allowed.has(requestOrigin)) {
    return requestOrigin
  }
  return "*"
}

export function applyCorsHeaders(response: NextResponse, origin: string | null, methods = "POST, OPTIONS") {
  const resolvedOrigin = resolveCorsOrigin(origin)
  response.headers.set("Access-Control-Allow-Origin", resolvedOrigin)
  response.headers.set("Access-Control-Allow-Methods", methods)
  response.headers.set("Access-Control-Allow-Headers", "Content-Type, Authorization")
  response.headers.set("Access-Control-Max-Age", "86400")
  response.headers.set("Vary", "Origin")
  return response
}

export function createCorsPreflight(origin: string | null, methods = "POST, OPTIONS") {
  const response = new NextResponse(null, { status: 204 })
  return applyCorsHeaders(response, origin, methods)
}

export function jsonWithCors<T>(data: T, init: number | ResponseInit, origin: string | null, methods = "POST, OPTIONS") {
  const response = NextResponse.json(data, typeof init === "number" ? { status: init } : init)
  return applyCorsHeaders(response, origin, methods)
}
