import 'server-only'

import { createAdminClient } from '@/lib/supabase/admin'
import { logOperationEvent } from '@/lib/observability/operation-events'
import type { OperationDetail } from '@/lib/domain/operation-log'

/**
 * Auto-Participant audit trail (§34, 2026-09-30): who created a rule, who
 * accepted it, when it became active, who disabled it, which trips it
 * touched. Best effort — never throws, never blocks the workflow. Every row
 * is mirrored into operation_events so /admin/operations shows it.
 */
export type AutoParticipantRuleEventName =
  | 'rule_requested'
  | 'rule_created'
  | 'rule_resent'
  | 'rule_cancelled'
  | 'rule_accepted'
  | 'rule_declined'
  | 'rule_disabled'
  | 'rule_reactivated'
  | 'rule_removed'
  | 'rule_scope_changed'
  | 'rule_suspended'
  | 'rule_stopped_by_participant'
  | 'participant_added'
  | 'participant_already_present'
  | 'participant_skipped'
  | 'participant_removed_from_trip'

export interface Actor { id: string | null; label: string }

export async function logAutoParticipantRuleEvent(params: {
  ruleId: string
  event: AutoParticipantRuleEventName
  actor?: Actor | null
  tripId?: string | null
  participantId?: string | null
  detail?: Record<string, unknown>
}): Promise<void> {
  const row = {
    rule_id: params.ruleId,
    event: params.event,
    actor_user_id: params.actor?.id ?? null,
    actor_label: params.actor?.label ?? 'system',
    trip_id: params.tripId ?? null,
    participant_id: params.participantId ?? null,
    detail: params.detail ?? {},
  }
  try {
    const { error } = await createAdminClient().from('auto_participant_rule_events').insert(row)
    if (error) console.error('auto_participant_rule_events insert failed', { event: row.event, code: error.code })
  } catch (error) {
    console.error('auto_participant_rule_events unavailable', { event: row.event, type: error instanceof Error ? error.name : 'unknown' })
  }
  await logOperationEvent({
    area: 'system',
    event: `auto_participant_${params.event}`,
    outcome: params.event === 'participant_skipped' ? 'skipped' : 'success',
    tripId: params.tripId ?? null,
    detail: { rule_id: params.ruleId, actor: row.actor_label, ...(params.detail ?? {}) } as OperationDetail,
  })
}
