import apiService from './apiService';

export interface TwoFactorStatus {
  enabled_globally: boolean;
  required_for_user: boolean;
  method: string | null;
  otp_app: boolean;
}

const baseURL = import.meta.env.VITE_FRAPPE_BASE_URL || '';

export async function fetchTwoFactorStatus(user?: string): Promise<TwoFactorStatus> {
  const csrf = await apiService.getCSRFTokenForGuest();
  const headers: Record<string, string> = {
    Accept: 'application/json',
    'Content-Type': 'application/json',
  };
  if (csrf) headers['X-Frappe-CSRF-Token'] = csrf;

  const response = await fetch(
    `${baseURL}/api/method/asm_ui_app.api.two_factor.get_two_factor_status`,
    {
      method: 'POST',
      credentials: 'include',
      headers,
      body: JSON.stringify(user ? { user } : {}),
    }
  );

  const data = await response.json();
  if (!response.ok) {
    const msg =
      typeof data.message === 'string'
        ? data.message
        : data.exc || 'Failed to load two-factor status';
    throw new Error(msg);
  }
  return data.message as TwoFactorStatus;
}

export async function resetOtpSecret(user: string): Promise<void> {
  const csrf = await apiService.getCSRFTokenForGuest();
  const headers: Record<string, string> = {
    Accept: 'application/json',
    'Content-Type': 'application/json',
  };
  if (csrf) headers['X-Frappe-CSRF-Token'] = csrf;

  const response = await fetch(
    `${baseURL}/api/method/frappe.twofactor.reset_otp_secret`,
    {
      method: 'POST',
      credentials: 'include',
      headers,
      body: JSON.stringify({ user }),
    }
  );

  const data = await response.json();
  if (!response.ok) {
    const msg =
      typeof data.message === 'string'
        ? data.message
        : data.exc || 'Failed to reset OTP secret';
    throw new Error(msg);
  }
}
