import type { IiosPlatformPorts } from '@insignia/iios-contracts';
import type { IiosMeetingParticipant } from '@prisma/client';

export interface ConsentVerdict {
  allowed: boolean;
  reason?: string;
  receiptRef?: string;
}

/**
 * The P8 safety spine (Critics KG-14 / Scenario 6). A recording artifact
 * (transcript / summary / action items) may exist ONLY when **every** participant
 * has GRANTED recording consent AND the CMP purpose check does not DENY. Anything
 * else fails closed. This is deliberately unanimous: one non-consenting attendee
 * blocks the whole recording.
 */
export async function checkMeetingConsent(
  ports: IiosPlatformPorts,
  meetingId: string,
  participants: Pick<IiosMeetingParticipant, 'recordingConsent'>[],
): Promise<ConsentVerdict> {
  const cmp = await ports.cmp.checkPurpose({ purpose: 'meeting_recording', meetingId });
  if (cmp.status === 'DENY') return { allowed: false, reason: 'CMP_DENIED' };

  const nonConsenting = participants.filter((p) => p.recordingConsent !== 'GRANTED');
  if (nonConsenting.length > 0) {
    return { allowed: false, reason: 'ATTENDEE_CONSENT_MISSING' };
  }
  return { allowed: true, receiptRef: cmp.receiptRef };
}
