import { NextRequest, NextResponse } from 'next/server'
import { createAdminClient } from '@/lib/supabase/admin'
import { parseZeptoMailWebhook } from '@/lib/domain/zeptomail-webhook'
import { applyDeliveryEvents, pilotNetworkAvailable } from '@/lib/data/pilot-network'

/**
 * ZeptoMail → HeavyHaul Agent delivery webhook (2026-09-15). In the agent's
 * Webhooks tab:
 *
 *   Webhook URL            https://heavyhaulgbt.com/api/pilot/email-webhook
 *   Authorization headers  x-pilot-webhook-secret = <PILOT_WEBHOOK_SECRET>
 *   Events                 Soft bounces · Hard bounces · Feedback loop
 *
 * (`?key=<secret>` on the URL works too.) ZeptoMail's rules: unauthenticated
 * from its side, POST only, must answer 200 — so once the secret matches the
 * route always answers 200, even when the database is not ready, and the
 * "Verify" call (an empty or sample payload) succeeds. Hard bounces and
 * complaints go on the suppression list (§23) and into the invitation
 * history (§24); soft bounces are recorded only.
 */
function authorised(req: NextRequest): boolean {
  const secret = process.env.PILOT_WEBHOOK_SECRET
  if (!secret) return false
  return req.headers.get('x-pilot-webhook-secret') === secret || req.nextUrl.searchParams.get('key') === secret
}

export async function GET(req: NextRequest) {
  if (!authorised(req)) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
  return NextResponse.json({ ok: true, service: 'HeavyHaul Agent pilot email webhook' })
}

export async function POST(req: NextRequest) {
  if (!authorised(req)) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
  const payload = await req.json().catch(() => null)
  const events = parseZeptoMailWebhook(payload)
  if (events.length === 0) return NextResponse.json({ ok: true, matched: 0, unmatched: 0, suppressed: 0, note: 'no recipient events in payload' })
  const admin = createAdminClient()
  if (!(await pilotNetworkAvailable(admin))) return NextResponse.json({ ok: false, error: 'Migration 0018 not applied — event not stored' })
  const result = await applyDeliveryEvents(events, payload, admin)
  return NextResponse.json({ ok: true, ...result })
}
