import 'server-only'

import { createHash } from 'node:crypto'
import { createAdminClient } from '@/lib/supabase/admin'
import { sendPlatformEmail } from '@/lib/email/send'
import { logOperationEvent } from '@/lib/observability/operation-events'
import { workspaceDimensionAlertsEnabled } from '@/lib/domain/dimension-alerts'
import type { ComputedWarning } from '@/lib/domain/warnings'
import type { Permit, Trip } from '@/types/db'

const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/

export interface DimensionAlertResult {
  sent: number
  skipped: number
  failed: number
}

export function dimensionAlertFingerprint(warnings: ComputedWarning[]): string | null {
  const messages = warnings
    .filter((warning) => warning.kind === 'dimension_mismatch')
    .map((warning) => warning.message)
    .sort()
  return messages.length
    ? createHash('sha256').update(messages.join('\n')).digest('hex')
    : null
}

/** Send one Workspace transactional email per distinct mismatch and contact. */
export async function sendPermitDimensionAlerts(params: {
  trip: Trip
  permit: Permit
  warnings: ComputedWarning[]
  origin: string
}): Promise<DimensionAlertResult> {
  const mismatches = params.warnings.filter((warning) => warning.kind === 'dimension_mismatch')
  const record = (outcome: 'success' | 'skipped' | 'failed', detail: Record<string, string | number | boolean | null>) => logOperationEvent({
    area: 'permit', event: 'dimension_alert_checked', outcome,
    tripId: params.trip.id, permitId: params.permit.id,
    detail: { mismatch_count: mismatches.length, ...detail },
  })
  if (!workspaceDimensionAlertsEnabled()) {
    await record('skipped', { reason: 'dimension_alert_paused', eligible_recipients: 0, sent: 0 })
    return { sent: 0, skipped: 0, failed: 0 }
  }
  if (!mismatches.length) {
    await record('skipped', { reason: 'no_dimension_mismatch', eligible_recipients: 0, sent: 0 })
    return { sent: 0, skipped: 0, failed: 0 }
  }

  const fingerprint = dimensionAlertFingerprint(mismatches)!
  const admin = createAdminClient()
  const { data: participants, error } = await admin.from('trip_participants')
    .select('email, role, status, user_id').eq('trip_id', params.trip.id)
    .in('role', ['broker', 'dispatcher'])
  if (error) {
    console.error('Dimension alert contacts unavailable:', error.message)
    await record('failed', { reason: 'contacts_unavailable', eligible_recipients: 0, sent: 0 })
    return { sent: 0, skipped: 0, failed: 1 }
  }

  const result: DimensionAlertResult = { sent: 0, skipped: 0, failed: 0 }
  const seen = new Set<string>()
  const eligible = (participants ?? []).filter((participant) => participant.status === 'active' || participant.status === 'invited')
  const excludedImported = (participants ?? []).filter((participant) => participant.status === 'imported').length
  if (!eligible.length) {
    await record('skipped', { reason: 'no_eligible_recipients', eligible_recipients: 0, imported_contacts: excludedImported, sent: 0 })
    return result
  }
  for (const participant of eligible) {
    const email = participant.email?.trim().toLowerCase()
    if (!email || !EMAIL.test(email) || seen.has(email)) continue
    seen.add(email)

    // The unique key reserves this exact alert. A callback retry or concurrent
    // request sees 23505 and does not send a duplicate email.
    const { data: reservation, error: reserveError } = await admin
      .from('permit_dimension_alert_deliveries')
      .insert({ permit_id: params.permit.id, recipient_email: email, alert_fingerprint: fingerprint })
      .select('id').single()
    if (reserveError?.code === '23505') { result.skipped++; continue }
    if (reserveError || !reservation) {
      console.error('Dimension alert could not be reserved:', reserveError?.message)
      result.failed++
      continue
    }

    const rolePath = participant.role === 'broker' ? 'fb-trip-workspace' : 'cd-trip-workspace'
    const delivery = await sendPlatformEmail({
      templateKey: 'permit_dimension_alert',
      to: email,
      userId: participant.user_id,
      origin: params.origin,
      data: {
        trip_id: params.trip.ref_code,
        permit_number: params.permit.permit_number || 'Pending number',
        permit_state: params.permit.state_code || 'Unknown state',
        permit_source: params.permit.source_system === 'synchron' ? 'Synchron Permits' : 'Workspace upload',
        mismatch_rows: mismatches.map((warning) => `- ${warning.message}`).join('\n'),
        workspace_link: `${params.origin}/${rolePath}/${encodeURIComponent(params.trip.ref_code)}`,
      },
      tags: { kind: 'dimension_mismatch', trip: params.trip.ref_code, permit: params.permit.id },
    })

    if (delivery.status === 'sent') {
      await admin.from('permit_dimension_alert_deliveries').update({
        status: 'sent', sent_at: new Date().toISOString(), email_message_id: delivery.messageId ?? null,
      }).eq('id', reservation.id)
      result.sent++
    } else if (delivery.status === 'suppressed') {
      await admin.from('permit_dimension_alert_deliveries').update({ status: 'suppressed' }).eq('id', reservation.id)
      result.skipped++
    } else {
      // No provider or a temporary provider failure must remain retryable.
      await admin.from('permit_dimension_alert_deliveries').delete().eq('id', reservation.id)
      result.failed++
    }
  }
  await record(result.failed ? 'failed' : result.sent ? 'success' : 'skipped', {
    reason: result.failed ? 'delivery_failed' : result.sent ? 'sent' : seen.size ? 'duplicate_or_suppressed' : 'no_valid_email',
    eligible_recipients: seen.size,
    imported_contacts: excludedImported,
    sent: result.sent,
    skipped: result.skipped,
    failed: result.failed,
  })
  return result
}
