/**
 * Hook for validating approvers during step transitions
 */

import { searchUsers, ensureUserExists } from '@/services/userApi';

interface ValidationResult {
  success: boolean;
  error?: {
    type: 'self-assign' | 'not-found' | 'error';
    email: string;
    message: string;
  };
}

/**
 * Validate a single approver
 */
async function validateApprover(
  approver: any,
  initiatorEmail: string
): Promise<ValidationResult> {
  // Check if approver email matches initiator email
  if (approver.email.toLowerCase() === initiatorEmail.toLowerCase()) {
    return {
      success: false,
      error: {
        type: 'self-assign',
        email: approver.email,
        message: '',
      },
    };
  }

  try {
    // Search for user in Okta directory
    const response = await searchUsers(approver.email, 1);
    const searchResults = response.data?.data || [];

    if (searchResults.length === 0) {
      return {
        success: false,
        error: {
          type: 'not-found',
          email: approver.email,
          message: '',
        },
      };
    }

    const foundUser = searchResults[0];
    if (!foundUser) {
      return {
        success: false,
        error: {
          type: 'error',
          email: approver.email,
          message: 'Could not retrieve user details. Please try again.',
        },
      };
    }

    // Ensure user exists in database
    await ensureUserExists({
      userId: foundUser.userId,
      email: foundUser.email,
      displayName: foundUser.displayName,
      firstName: foundUser.firstName,
      lastName: foundUser.lastName,
      department: foundUser.department,
      phone: foundUser.phone,
      mobilePhone: foundUser.mobilePhone,
      designation: foundUser.designation,
      jobTitle: foundUser.jobTitle,
      manager: foundUser.manager,
      employeeId: foundUser.employeeId,
      employeeNumber: foundUser.employeeNumber,
      secondEmail: foundUser.secondEmail,
      location: foundUser.location,
    });

    return {
      success: true,
    };
  } catch (error) {
    console.error(`Failed to validate approver ${approver.email}:`, error);
    return {
      success: false,
      error: {
        type: 'error',
        email: approver.email,
        message: 'Failed to validate user. Please try again or select a different user.',
      },
    };
  }
}

/**
 * Validate all approvers that need validation
 */
export async function validateApprovers(
  approvers: any[],
  initiatorEmail: string
): Promise<{
  success: boolean;
  validatedApprovers?: any[];
  error?: {
    type: 'self-assign' | 'not-found' | 'error';
    email: string;
    message: string;
  };
}> {
  const approversToValidate = approvers.filter(
    (a) => a && a.email && !a.userId
  );

  if (approversToValidate.length === 0) {
    return { success: true, validatedApprovers: approvers };
  }

  const updatedApprovers = [...approvers];

  for (let i = 0; i < updatedApprovers.length; i++) {
    const approver = updatedApprovers[i];

    // Skip if already has userId (selected via @ search)
    if (approver.userId || !approver.email) continue;

    const validation = await validateApprover(approver, initiatorEmail);

    if (!validation.success) {
      return {
        success: false,
        error: validation.error,
      };
    }

    // Update approver with validated data
    try {
      const response = await searchUsers(approver.email, 1);
      const searchResults = response.data?.data || [];
      const foundUser = searchResults[0];

      if (foundUser) {
        const dbUser = await ensureUserExists({
          userId: foundUser.userId,
          email: foundUser.email,
          displayName: foundUser.displayName,
          firstName: foundUser.firstName,
          lastName: foundUser.lastName,
          department: foundUser.department,
          phone: foundUser.phone,
          mobilePhone: foundUser.mobilePhone,
          designation: foundUser.designation,
          jobTitle: foundUser.jobTitle,
          manager: foundUser.manager,
          employeeId: foundUser.employeeId,
          employeeNumber: foundUser.employeeNumber,
          secondEmail: foundUser.secondEmail,
          location: foundUser.location,
        });

        updatedApprovers[i] = {
          ...approver,
          userId: dbUser.userId,
          name: dbUser.displayName || approver.name,
          department: dbUser.department || approver.department,
          avatar: (dbUser.displayName || dbUser.email)
            .substring(0, 2)
            .toUpperCase(),
        };
      }
    } catch (error) {
      console.error(`Failed to update approver ${approver.email}:`, error);
    }
  }

  return {
    success: true,
    validatedApprovers: updatedApprovers,
  };
}

