import { NextResponse } from "next/server"

import { assertAdminSession } from "@/lib/auth-server"
import { DEFAULT_TENANT_ID } from "@/lib/constants"
import { env } from "@/lib/env"
import { runReportSchedules } from "@/server/report-schedule-runner"

export const runtime = "nodejs"

export async function POST(request: Request) {
  const payload = (await request.json().catch(() => ({}))) as {
    scheduleId?: string
    tenantId?: string
  }

  const session = await assertAdminSession()
  const cronAuthorized = isCronRequest(request)

  if (!session && !cronAuthorized) {
    return NextResponse.json({ error: "Não autorizado" }, { status: 401 })
  }

  const tenantId = session ? session.user.tenantId ?? DEFAULT_TENANT_ID : payload.tenantId

  const result = await runReportSchedules({
    tenantId,
    scheduleId: payload.scheduleId,
    initiatedBy: session
      ? {
          userId: session.user.id,
          name: session.user.name,
          email: session.user.email,
          avatarUrl: session.user.avatarUrl,
          role: session.user.role,
        }
      : {
          name: "Report Scheduler",
          email: env.SMTP?.from ?? "scheduler@sistema.local",
          role: "ADMIN",
        },
  })

  return NextResponse.json(result)
}

function isCronRequest(request: Request) {
  const secret = env.REPORTS_CRON_SECRET
  if (!secret) return false
  const auth = request.headers.get("authorization")
  if (auth && auth === `Bearer ${secret}`) return true
  const header = request.headers.get("x-cron-secret")
  if (header && header === secret) return true
  const url = new URL(request.url)
  if (url.searchParams.get("secret") === secret) return true
  return false
}
