import { Blocker } from './Blocker';
import type { PolicySnapshotDto } from '../api/policy/PolicyApiClient';
import { PolicyService } from '../services/policy/PolicyService';

export type CapabilityBlockReason = 'loading' | 'enabled' | 'coming_soon' | 'disabled' | 'hidden';

export class CapabilityBlocker extends Blocker {
  private snapshot: PolicySnapshotDto | null = null;

  constructor(
    private readonly policyService: PolicyService,
    private readonly capabilityKey: string,
  ) {
    super();
  }

  updateSnapshot(snapshot: PolicySnapshotDto | null): void {
    this.snapshot = snapshot;
  }

  canExecute(): boolean {
    return this.getReason() === 'enabled';
  }

  getReason(): CapabilityBlockReason {
    if (!this.snapshot) {
      return 'loading';
    }

    return this.policyService.getCapabilityState(this.snapshot, this.capabilityKey);
  }

  block(): void {
    this.snapshot = {
      ...(this.snapshot ?? {
        policyVersion: 0,
        operationalMode: 'normal',
        maintenanceAllowlist: { view: [], mutate: [] },
        capabilities: {},
        loadedFrom: 'defaults',
        loadedAtIso: new Date().toISOString(),
      }),
      capabilities: {
        ...(this.snapshot?.capabilities ?? {}),
        [this.capabilityKey]: 'disabled',
      },
    };
  }

  release(): void {
    this.snapshot = {
      ...(this.snapshot ?? {
        policyVersion: 0,
        operationalMode: 'normal',
        maintenanceAllowlist: { view: [], mutate: [] },
        capabilities: {},
        loadedFrom: 'defaults',
        loadedAtIso: new Date().toISOString(),
      }),
      capabilities: {
        ...(this.snapshot?.capabilities ?? {}),
        [this.capabilityKey]: 'enabled',
      },
    };
  }
}