import axios from 'axios';

const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3020';

export interface MFAStatus {
  enabled: boolean;
  method?: 'totp' | 'email';
  hasBackupCodes: boolean;
}

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

export const mfaApi = {
  // Get MFA status
  async getStatus(): Promise<MFAStatus> {
    const response = await axios.get(`${API_BASE_URL}/api/v1/auth/mfa/status`, {
      headers: {
        Authorization: `Bearer ${localStorage.getItem('accessToken')}`,
      },
    });
    return response.data;
  },

  // Setup TOTP (Google Authenticator)
  async setupTOTP(): Promise<TOTPSetupResult> {
    const response = await axios.post(
      `${API_BASE_URL}/api/v1/auth/mfa/totp/setup`,
      {},
      {
        headers: {
          Authorization: `Bearer ${localStorage.getItem('accessToken')}`,
        },
      }
    );
    return response.data;
  },

  // Enable TOTP
  async enableTOTP(code: string): Promise<{ success: boolean; message: string }> {
    const response = await axios.post(
      `${API_BASE_URL}/api/v1/auth/mfa/totp/enable`,
      { code },
      {
        headers: {
          Authorization: `Bearer ${localStorage.getItem('accessToken')}`,
        },
      }
    );
    return response.data;
  },

  // Setup Email MFA
  async setupEmailMFA(): Promise<{ success: boolean; message: string }> {
    const response = await axios.post(
      `${API_BASE_URL}/api/v1/auth/mfa/email/setup`,
      {},
      {
        headers: {
          Authorization: `Bearer ${localStorage.getItem('accessToken')}`,
        },
      }
    );
    return response.data;
  },

  // Disable MFA
  async disableMFA(): Promise<{ success: boolean; message: string }> {
    const response = await axios.delete(`${API_BASE_URL}/api/v1/auth/mfa`, {
      headers: {
        Authorization: `Bearer ${localStorage.getItem('accessToken')}`,
      },
    });
    return response.data;
  },

  // Regenerate backup codes
  async regenerateBackupCodes(): Promise<{ success: boolean; backupCodes: string[] }> {
    const response = await axios.post(
      `${API_BASE_URL}/api/v1/auth/mfa/backup-codes/regenerate`,
      {},
      {
        headers: {
          Authorization: `Bearer ${localStorage.getItem('accessToken')}`,
        },
      }
    );
    return response.data;
  },
};
