import 'server-only'

import { createAdminClient } from '@/lib/supabase/admin'
import { logTripEvent } from '@/lib/audit'
import { logAutoParticipantRuleEvent } from '@/lib/data/auto-participant-events'
import { canRemoveParticipant } from '@/lib/domain/participants'
import type { TripParticipant, TripRole } from '@/types/db'

/**
 * Remove a participant from a live trip (decision D17, 2026-09-30). Who may:
 * `canRemoveParticipant`. The person stops being on THIS trip; their
 * Auto-Participant rule is not changed (§20). Pilots keep their own route
 * (`pilot-remove`, which also expires the open invitation).
 */
export async function removeParticipantFromTrip(params: {
  tripId: string
  participantId: string
  viewer: { userId: string | null; role: TripRole | string; isAdmin: boolean; label: string; activeCompanyId?: string | null; activeIsCompanyAdmin?: boolean }
}): Promise<{ ok: true; participant: TripParticipant } | { ok: false; error: string; status: number }> {
  const admin = createAdminClient()
  const { data } = await admin.from('trip_participants').select('*').eq('id', params.participantId).eq('trip_id', params.tripId).maybeSingle()
  const target = data as TripParticipant | null
  if (!target) return { ok: false, error: 'Participant not found.', status: 404 }
  if (target.status === 'removed') return { ok: false, error: 'Already removed.', status: 409 }
  if (!canRemoveParticipant({ viewer: params.viewer, target })) {
    return { ok: false, error: 'You cannot remove this participant.', status: 403 }
  }
  const { error } = await admin.from('trip_participants').update({ status: 'removed' }).eq('id', target.id)
  if (error) return { ok: false, error: 'Could not remove the participant.', status: 500 }
  // A pending invitation link must not revive the row (same rule as pilot-remove).
  await admin.from('trip_invitations').update({ expires_at: new Date(0).toISOString() }).eq('participant_id', target.id).is('accepted_at', null)
  await logTripEvent({
    tripId: params.tripId,
    actorId: params.viewer.userId,
    actorLabel: params.viewer.label,
    action: 'participant_removed',
    detail: { participant_id: target.id, email: target.email, role: target.role, addition_method: target.addition_method ?? null, auto_participant_rule_id: target.auto_participant_rule_id ?? null },
  })
  if (target.auto_participant_rule_id) {
    await logAutoParticipantRuleEvent({ ruleId: target.auto_participant_rule_id, event: 'participant_removed_from_trip', actor: { id: params.viewer.userId, label: params.viewer.label }, tripId: params.tripId, participantId: target.id })
  }
  return { ok: true, participant: { ...target, status: 'removed' } }
}
