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

type CmpPort = IiosPlatformPorts['cmp'];
type CmpStatus = 'ALLOW' | 'DENY' | 'NOT_REQUIRED';

/** Deterministic CMP (consent) fake. Defaults to NOT_REQUIRED; supports purpose-aware decisions. */
export class FakeCmp implements CmpPort {
  private status: CmpStatus = 'NOT_REQUIRED';
  private deniedPurposes = new Set<string>();
  private allowedPurpose?: string;

  setStatus(s: CmpStatus): this {
    this.status = s;
    return this;
  }

  /** Deny one specific purpose while other purposes follow the default status. */
  denyPurpose(purpose: string): this {
    this.deniedPurposes.add(purpose);
    return this;
  }

  /** Allow only this purpose; every other purpose is denied. */
  allowOnly(purpose: string): this {
    this.allowedPurpose = purpose;
    return this;
  }

  async checkPurpose(input: unknown): Promise<{ receiptRef?: string; status: CmpStatus }> {
    const purpose = (input as { purpose?: string } | undefined)?.purpose;
    let status = this.status;
    if (purpose && this.deniedPurposes.has(purpose)) status = 'DENY';
    if (this.allowedPurpose !== undefined) status = purpose === this.allowedPurpose ? 'ALLOW' : 'DENY';
    return { receiptRef: status === 'ALLOW' ? 'fake-receipt' : undefined, status };
  }
}
