/**
 * use2FA Hook
 * React Query hooks for Two-Factor Authentication
 * @created Sprint 2 - TASK-2026-01-30-ANALISIS-INTEGRACION
 */

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

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

export interface TwoFactorStatus {
  enabled: boolean;
  method: '2fa_totp' | null;
  backupCodesRemaining: number;
}

export interface TwoFactorSetupResponse {
  secret: string;
  qrCodeUrl: string;
  backupCodes: string[];
}

export interface VerifyCodeInput {
  code: string;
}

export interface RegenerateBackupCodesResponse {
  backupCodes: string[];
}

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

async function get2FAStatus(): Promise<TwoFactorStatus> {
  const response = await apiClient.get('/auth/2fa/status');
  return response.data.data;
}

async function setup2FA(): Promise<TwoFactorSetupResponse> {
  const response = await apiClient.post('/auth/2fa/setup');
  return response.data.data;
}

async function enable2FA(code: string): Promise<{ message: string }> {
  const response = await apiClient.post('/auth/2fa/enable', { code });
  return response.data;
}

async function disable2FA(code: string): Promise<{ message: string }> {
  const response = await apiClient.post('/auth/2fa/disable', { code });
  return response.data;
}

async function regenerateBackupCodes(code: string): Promise<RegenerateBackupCodesResponse> {
  const response = await apiClient.post('/auth/2fa/backup-codes', { code });
  return response.data.data;
}

// ============================================================================
// React Query Hooks
// ============================================================================

/**
 * Get 2FA status for current user
 */
export function use2FAStatus() {
  return useQuery({
    queryKey: ['2fa', 'status'],
    queryFn: get2FAStatus,
    staleTime: 5 * 60 * 1000, // 5 minutes
  });
}

/**
 * Setup 2FA - generates secret, QR code, and backup codes
 */
export function useSetup2FA() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: setup2FA,
    onSuccess: () => {
      // Invalidate status after setup
      queryClient.invalidateQueries({ queryKey: ['2fa', 'status'] });
    },
  });
}

/**
 * Enable 2FA with verification code
 */
export function useEnable2FA() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (code: string) => enable2FA(code),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['2fa', 'status'] });
    },
  });
}

/**
 * Disable 2FA with verification code
 */
export function useDisable2FA() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (code: string) => disable2FA(code),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['2fa', 'status'] });
    },
  });
}

/**
 * Regenerate backup codes with current TOTP code
 */
export function useRegenerateBackupCodes() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (code: string) => regenerateBackupCodes(code),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['2fa', 'status'] });
    },
  });
}

// ============================================================================
// Helper Functions
// ============================================================================

/**
 * Format backup code for display (e.g., "ABCD-1234")
 */
export function formatBackupCode(code: string): string {
  if (code.includes('-')) return code;
  if (code.length === 8) {
    return `${code.slice(0, 4)}-${code.slice(4)}`;
  }
  return code;
}

/**
 * Get user-friendly 2FA status label
 */
export function get2FAStatusLabel(status: TwoFactorStatus | undefined): string {
  if (!status) return 'Loading...';
  if (status.enabled) {
    return `Enabled (${status.backupCodesRemaining} backup codes remaining)`;
  }
  return 'Not enabled';
}

// ============================================================================
// Export
// ============================================================================

export const twoFactorHooks = {
  use2FAStatus,
  useSetup2FA,
  useEnable2FA,
  useDisable2FA,
  useRegenerateBackupCodes,
  formatBackupCode,
  get2FAStatusLabel,
};

export default twoFactorHooks;
