import { SystemPolicy, FormData } from './useCreateRequestForm';

export interface PolicyViolation {
  type: string;
  message: string;
  currentValue?: number;
  maxValue?: number;
}

/**
 * Custom Hook: usePolicyValidation
 * 
 * Purpose: Validates actions against system policies
 * 
 * Responsibilities:
 * - Validates approver additions against policy limits
 * - Validates spectator additions against policy limits
 * - Checks for duplicate users across roles
 * - Returns policy violations for display
 */
export function usePolicyValidation(systemPolicy: SystemPolicy) {
  const validateAddApprover = (
    formData: FormData,
    newApprover: any
  ): PolicyViolation[] => {
    const violations: PolicyViolation[] = [];
    const updatedApprovers = [...formData.approvers, newApprover];
    const maxLevel = Math.max(...updatedApprovers.map((a: any) => a.level || 1), 1);

    if (maxLevel > systemPolicy.maxApprovalLevels) {
      violations.push({
        type: 'Maximum Approval Levels Exceeded',
        message: `Adding this approver would exceed the maximum approval levels limit.`,
        currentValue: maxLevel,
        maxValue: systemPolicy.maxApprovalLevels
      });
    }

    const totalParticipants = 1 + updatedApprovers.length + formData.spectators.length;
    if (totalParticipants > systemPolicy.maxParticipants) {
      violations.push({
        type: 'Maximum Participants Exceeded',
        message: `Adding this approver would exceed the maximum participants limit.`,
        currentValue: totalParticipants,
        maxValue: systemPolicy.maxParticipants
      });
    }

    return violations;
  };

  const validateAddSpectator = (
    formData: FormData,
    newSpectator: any
  ): PolicyViolation[] => {
    const violations: PolicyViolation[] = [];

    if (!systemPolicy.allowSpectators) {
      violations.push({
        type: 'Spectators Not Allowed',
        message: `Adding spectators is not allowed by system policy.`,
      });
    }

    const updatedSpectators = [...formData.spectators, newSpectator];
    if (updatedSpectators.length > systemPolicy.maxSpectators) {
      violations.push({
        type: 'Maximum Spectators Exceeded',
        message: `Adding this spectator would exceed the maximum spectators limit.`,
        currentValue: updatedSpectators.length,
        maxValue: systemPolicy.maxSpectators
      });
    }

    const totalParticipants = 1 + formData.approvers.length + updatedSpectators.length;
    if (totalParticipants > systemPolicy.maxParticipants) {
      violations.push({
        type: 'Maximum Participants Exceeded',
        message: `Adding this spectator would exceed the maximum participants limit.`,
        currentValue: totalParticipants,
        maxValue: systemPolicy.maxParticipants
      });
    }

    return violations;
  };

  const checkDuplicateUser = (
    formData: FormData,
    user: any,
    targetType: 'approvers' | 'spectators'
  ): { isDuplicate: boolean; message?: string } => {
    const userEmail = (user.email || '').toLowerCase();
    const userId = user.id || user.userId;

    if (targetType === 'spectators') {
      const isApprover = formData.approvers.find((a: any) =>
        a.id === userId || (a.email || '').toLowerCase() === userEmail
      );
      if (isApprover) {
        return {
          isDuplicate: true,
          message: `${user.name || user.email} is already an approver and cannot be added as a spectator.`
        };
      }
    } else if (targetType === 'approvers') {
      const isSpectator = formData.spectators.find((s: any) =>
        s.id === userId || (s.email || '').toLowerCase() === userEmail
      );
      if (isSpectator) {
        return {
          isDuplicate: true,
          message: `${user.name || user.email} is already a spectator and cannot be added as an approver.`
        };
      }

      // Check if user is already another approver
      const isOtherApprover = formData.approvers.find((a: any) =>
        (a.id === userId || (a.email || '').toLowerCase() === userEmail) && a !== user
      );
      if (isOtherApprover) {
        return {
          isDuplicate: true,
          message: `${user.name || user.email} is already an approver at another level.`
        };
      }
    }

    // Check if already in target list
    const currentList = formData[targetType];
    const isInList = currentList.find((u: any) =>
      u.id === userId || (u.email || '').toLowerCase() === userEmail
    );
    if (isInList) {
      return {
        isDuplicate: true,
        message: `${user.name || user.email} is already added as ${targetType.slice(0, -1)}.`
      };
    }

    return { isDuplicate: false };
  };

  return {
    validateAddApprover,
    validateAddSpectator,
    checkDuplicateUser
  };
}

