import { Injectable } from '@nestjs/common';
import { IiosRouteDecisionState } from '@prisma/client';

export interface RuleFlag {
  flagType: string;
}

interface DecidableBinding {
  restrictionProfile: string | null;
  requiresReview: boolean;
}

/**
 * Deterministic routing rules (P6). Keyword-based moderation flags + a decision
 * function that is **deny-by-default for restricted destinations**. Versioned so
 * a past decision is reproducible on replay. AI may only *propose* flags later
 * (P7) — it can never turn a DENY/REVIEW into an ALLOW here.
 */
@Injectable()
export class RuleEngine {
  readonly rulepackVersion = 'v1';

  flag(text: string): RuleFlag[] {
    const t = (text ?? '').toLowerCase();
    const flags: RuleFlag[] = [];
    if (t.includes('party') || /\b(9|10|11)\s*pm\b/.test(t)) flags.push({ flagType: 'AFTER_HOURS_EVENT' });
    if (t.includes('sale') || t.includes('promo') || t.includes('discount')) flags.push({ flagType: 'PROMOTION' });
    return flags;
  }

  /** Destination profiles that are deny-by-default for any flagged content. */
  private readonly protectedProfiles = new Set(['CHILD']);

  decide(binding: DecidableBinding, flagTypes: string[]): { state: IiosRouteDecisionState; reasonCodes: string[] } {
    const protectedDest = !!binding.restrictionProfile && this.protectedProfiles.has(binding.restrictionProfile);

    // Deny-by-default: a protected destination (e.g. CHILD) never receives flagged content.
    if (protectedDest && flagTypes.length > 0) {
      return { state: 'DENY', reasonCodes: [`${binding.restrictionProfile}_GROUP_RESTRICTION`, ...flagTypes] };
    }
    if (flagTypes.length > 0) {
      return { state: 'REVIEW', reasonCodes: [...flagTypes, 'ADMIN_APPROVAL_REQUIRED'] };
    }
    if (binding.requiresReview) {
      return { state: 'REVIEW', reasonCodes: ['ADMIN_APPROVAL_REQUIRED'] };
    }
    return { state: 'ALLOW', reasonCodes: [] };
  }
}
