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

type OpaPort = IiosPlatformPorts['opa'];

/** Deterministic OPA fake. Defaults to allow; can be set to deny or timeout. */
export class FakeOpa implements OpaPort {
  private decision: PolicyDecision = {
    decisionRef: 'fake-allow',
    allow: true,
    obligations: [],
    ttlSeconds: 60,
  };
  private mode: 'normal' | 'timeout' = 'normal';

  setDecision(d: Partial<PolicyDecision>): this {
    this.decision = { ...this.decision, ...d };
    return this;
  }

  deny(reason = 'denied by fake opa'): this {
    this.decision = {
      decisionRef: 'fake-deny',
      allow: false,
      obligations: [{ kind: 'AUDIT', reason }],
      ttlSeconds: 0,
    };
    return this;
  }

  timeout(): this {
    this.mode = 'timeout';
    return this;
  }

  async decide(_input: unknown): Promise<PolicyDecision> {
    if (this.mode === 'timeout') throw new Error('opa timeout');
    return this.decision;
  }
}
