/**
 * useKYCStatus Hook
 * TanStack Query hooks for KYC verification status
 * Epic: OQI-004 Cuentas de Inversion
 */

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { apiClient } from '../../../lib/apiClient';
import type { KYCStatus } from '../components/KYCStatusBadge';

// ============================================================================
// Query Keys
// ============================================================================

export const kycKeys = {
  all: ['kyc'] as const,
  status: () => [...kycKeys.all, 'status'] as const,
};

// ============================================================================
// Types
// ============================================================================

export interface KYCData {
  status: KYCStatus;
  personalData?: {
    fullName: string;
    dateOfBirth: string;
    nationality: string;
    address: string;
    city: string;
    state: string;
    postalCode: string;
    country: string;
    occupation: string;
    incomeSource: string;
  };
  documents?: Array<{
    id: string;
    type: 'id_front' | 'id_back' | 'proof_of_address' | 'selfie';
    fileName: string;
    status: 'pending' | 'approved' | 'rejected';
    rejectionReason?: string;
  }>;
  rejectionReason?: string;
  submittedAt?: string;
  reviewedAt?: string;
}

export interface KYCSubmitData {
  personalData: {
    fullName: string;
    dateOfBirth: string;
    nationality: string;
    address: string;
    city: string;
    state: string;
    postalCode: string;
    country: string;
    occupation: string;
    incomeSource: string;
  };
  documents: File[];
}

// ============================================================================
// API Functions
// ============================================================================

async function getKYCStatus(): Promise<KYCData> {
  try {
    const response = await apiClient.get('/investment/kyc/status');
    return response.data.data || { status: 'not_started' };
  } catch (error: unknown) {
    const axiosError = error as { response?: { status: number } };
    if (axiosError.response?.status === 404) {
      return { status: 'not_started' };
    }
    throw error;
  }
}

async function submitKYC(data: KYCSubmitData): Promise<KYCData> {
  const formData = new FormData();
  formData.append('personalData', JSON.stringify(data.personalData));
  data.documents.forEach((file, index) => {
    formData.append(`document_${index}`, file);
  });

  const response = await apiClient.post('/investment/kyc/submit', formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  });
  return response.data.data;
}

// ============================================================================
// Hooks
// ============================================================================

/**
 * Hook to fetch KYC verification status
 */
export function useKYCStatus() {
  return useQuery<KYCData, Error>({
    queryKey: kycKeys.status(),
    queryFn: getKYCStatus,
    staleTime: 5 * 60 * 1000, // 5 minutes
    retry: (failureCount, error) => {
      // Don't retry on 404
      const axiosError = error as { response?: { status: number } };
      if (axiosError.response?.status === 404) return false;
      return failureCount < 3;
    },
  });
}

/**
 * Hook to submit KYC verification
 */
export function useSubmitKYC() {
  const queryClient = useQueryClient();

  return useMutation<KYCData, Error, KYCSubmitData>({
    mutationFn: submitKYC,
    onSuccess: (data) => {
      // Update the KYC status in the cache
      queryClient.setQueryData(kycKeys.status(), data);
    },
  });
}

/**
 * Check if KYC is complete (approved)
 */
export function useIsKYCApproved(): boolean {
  const { data } = useKYCStatus();
  return data?.status === 'approved';
}

/**
 * Check if KYC is in progress (pending or in_review)
 */
export function useIsKYCPending(): boolean {
  const { data } = useKYCStatus();
  return data?.status === 'pending' || data?.status === 'in_review';
}

export default useKYCStatus;
