import { Request, Response, NextFunction } from 'express';
import { MfaService } from './services/mfa.service.js';
import { ApiResponse, AuthenticatedRequest } from '../../shared/types/index.js';

export const mfaController = {
  /**
   * Initialize MFA setup
   */
  async setup(req: AuthenticatedRequest, res: Response, next: NextFunction) {
    try {
      const userId = req.user!.userId; // Assuming req.user is populated by auth middleware
      const result = await MfaService.setupMfa(userId);
      
      const response: ApiResponse = {
        success: true,
        data: result,
      };
      res.json(response);
    } catch (error) {
      next(error);
    }
  },

  /**
   * Verify MFA setup and enable
   */
  async verifySetup(req: AuthenticatedRequest, res: Response, next: NextFunction) {
    try {
      const userId = req.user!.userId;
      const { secret, code } = req.body;

      if (!secret || !code) {
        throw new Error('Secret and code are required'); // Should use Zod/Validation middleware ideally
      }

      const result = await MfaService.verifyMfaSetup(userId, secret, code);
      
      const response: ApiResponse = {
        success: true,
        message: result.message,
        data: { backupCodes: result.backupCodes },
      };
      res.json(response);
    } catch (error) {
      next(error);
    }
  },

  /**
   * Disable MFA
   */
  async disable(req: AuthenticatedRequest, res: Response, next: NextFunction) {
    try {
      const userId = req.user!.userId;
      const { code, password } = req.body;

      if (!code) {
         throw new Error('Verification code is required');
      }

      const result = await MfaService.disableMfa(userId, code, password);
      
      const response: ApiResponse = {
        success: true,
        message: result.message,
      };
      res.json(response);
    } catch (error) {
      next(error);
    }
  },

  /**
   * Get MFA status
   */
  async getStatus(req: AuthenticatedRequest, res: Response, next: NextFunction) {
    try {
      const userId = req.user!.userId;
      const result = await MfaService.getMfaStatus(userId);
      
      const response: ApiResponse = {
        success: true,
        data: result,
      };
      res.json(response);
    } catch (error) {
      next(error);
    }
  },

  /**
   * Regenerate backup codes
   */
  async regenerateBackupCodes(req: AuthenticatedRequest, res: Response, next: NextFunction) {
    try {
      const userId = req.user!.userId;
      const { code, password } = req.body;

      if (!code) {
         throw new Error('Verification code is required');
      }

      const result = await MfaService.regenerateBackupCodes(userId, code, password);
      
      const response: ApiResponse = {
        success: true,
        message: result.message,
        data: { backupCodes: result.backupCodes },
      };
      res.json(response);
    } catch (error) {
      next(error);
    }
  },
};
