import { Injectable } from '@angular/core';
import axios from 'axios';

import { BASE_URL } from '../config/api.config';

function authHeaders() {
  const token = localStorage.getItem('jwtToken');
  return { Authorization: `Bearer ${token}` };
}

export interface TwoFactorSetupResponse {
  userId: string;
  secretKey: string;
  qrCodeUrl: string;
  backupCodes: string[];
  enabled: boolean;
}

export interface TwoFactorStatus {
  enabled: boolean;
  hasBackupCodes?: boolean;
  backupCodesCount?: number;
}

@Injectable({ providedIn: 'root' })
export class TwoFactorAuthService {
  async setup2FA(): Promise<TwoFactorSetupResponse> {
    const res = await axios.post(`${BASE_URL}/api/v3/2fa/setup`, {}, { headers: authHeaders() });
    return res.data;
  }

  async enable2FA(code: string): Promise<void> {
    await axios.post(`${BASE_URL}/api/v3/2fa/enable`, { code }, { headers: authHeaders() });
  }

  async disable2FA(code: string): Promise<void> {
    await axios.post(`${BASE_URL}/api/v3/2fa/disable`, { code }, { headers: authHeaders() });
  }

  async get2FAStatus(): Promise<TwoFactorStatus> {
    const res = await axios.get(`${BASE_URL}/api/v3/2fa/status`, { headers: authHeaders() });
    return res.data;
  }

  async regenerateBackupCodes(code: string): Promise<string[]> {
    const res = await axios.post(`${BASE_URL}/api/v3/2fa/backup-codes/regenerate`, { code }, { headers: authHeaders() });
    return res.data.backupCodes || [];
  }

  async getQrCodeUrl(): Promise<string> {
    const res = await axios.get(`${BASE_URL}/api/v3/2fa/qr-code`, { headers: authHeaders() });
    return res.data.qrCodeUrl;
  }
}

