// ============================================================================
// OrbiQuant IA - Auth Routes
// ============================================================================

import { Router } from 'express';
import { validationResult } from 'express-validator';
import { Request, Response, NextFunction } from 'express';
import { authRateLimiter, strictRateLimiter } from '../../core/middleware/rate-limiter';
import { authenticate } from '../../core/middleware/auth.middleware';
import * as authController from './controllers/auth.controller';
import * as validators from './validators/auth.validators';

const router = Router();

// Validation middleware
const validate = (req: Request, res: Response, next: NextFunction) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({
      success: false,
      errors: errors.array().map((e) => ({
        field: e.type === 'field' ? (e as any).path : undefined,
        message: e.msg,
      })),
    });
  }
  next();
};

// Apply rate limiting
router.use(authRateLimiter);

// ============================================================================
// Email/Password Authentication
// ============================================================================

/**
 * POST /api/v1/auth/register
 * Register a new user with email/password
 */
router.post(
  '/register',
  strictRateLimiter,
  validators.registerValidator,
  validate,
  authController.register
);

/**
 * POST /api/v1/auth/login
 * Login with email/password
 */
router.post(
  '/login',
  strictRateLimiter,
  validators.loginValidator,
  validate,
  authController.login
);

/**
 * POST /api/v1/auth/verify-email
 * Verify email with token
 */
router.post(
  '/verify-email',
  validators.tokenValidator,
  validate,
  authController.verifyEmail
);

/**
 * POST /api/v1/auth/forgot-password
 * Request password reset email
 */
router.post(
  '/forgot-password',
  strictRateLimiter,
  validators.emailValidator,
  validate,
  authController.forgotPassword
);

/**
 * POST /api/v1/auth/reset-password
 * Reset password with token
 */
router.post(
  '/reset-password',
  validators.resetPasswordValidator,
  validate,
  authController.resetPassword
);

/**
 * POST /api/v1/auth/change-password
 * Change password (authenticated)
 */
router.post(
  '/change-password',
  authenticate,
  validators.changePasswordValidator,
  validate,
  authController.changePassword
);

// ============================================================================
// Phone Authentication (SMS/WhatsApp)
// ============================================================================

/**
 * POST /api/v1/auth/phone/send-otp
 * Send OTP to phone via SMS or WhatsApp
 */
router.post(
  '/phone/send-otp',
  strictRateLimiter,
  validators.phoneOTPValidator,
  validate,
  authController.sendPhoneOTP
);

/**
 * POST /api/v1/auth/phone/verify-otp
 * Verify OTP and login/register
 */
router.post(
  '/phone/verify-otp',
  validators.verifyPhoneOTPValidator,
  validate,
  authController.verifyPhoneOTP
);

// ============================================================================
// OAuth Authentication
// ============================================================================

/**
 * GET /api/v1/auth/:provider
 * Get OAuth authorization URL
 */
router.get(
  '/:provider',
  validators.oauthProviderValidator,
  validate,
  authController.getOAuthUrl
);

/**
 * GET /api/v1/auth/:provider/callback
 * OAuth callback handler
 */
router.get(
  '/:provider/callback',
  validators.oauthProviderValidator,
  validate,
  authController.handleOAuthCallback
);

/**
 * POST /api/v1/auth/:provider/callback
 * OAuth callback handler (POST for Apple)
 */
router.post(
  '/:provider/callback',
  validators.oauthProviderValidator,
  validate,
  authController.handleOAuthCallback
);

/**
 * POST /api/v1/auth/:provider/token
 * Verify OAuth token directly (for mobile apps)
 */
router.post(
  '/:provider/token',
  validators.oauthProviderValidator,
  validate,
  authController.verifyOAuthToken
);

// ============================================================================
// Token Management
// ============================================================================

/**
 * POST /api/v1/auth/refresh
 * Refresh access token
 */
router.post(
  '/refresh',
  validators.refreshTokenValidator,
  validate,
  authController.refreshToken
);

/**
 * POST /api/v1/auth/logout
 * Logout current session
 */
router.post('/logout', authenticate, authController.logout);

/**
 * POST /api/v1/auth/logout-all
 * Logout all sessions
 */
router.post('/logout-all', authenticate, authController.logoutAll);

/**
 * GET /api/v1/auth/sessions
 * Get active sessions
 */
router.get('/sessions', authenticate, authController.getSessions);

/**
 * DELETE /api/v1/auth/sessions/:sessionId
 * Revoke specific session
 */
router.delete(
  '/sessions/:sessionId',
  authenticate,
  validators.sessionIdValidator,
  validate,
  authController.revokeSession
);

// ============================================================================
// Two-Factor Authentication
// ============================================================================

/**
 * POST /api/v1/auth/2fa/setup
 * Set up 2FA (get QR code and backup codes)
 */
router.post('/2fa/setup', authenticate, authController.setup2FA);

/**
 * POST /api/v1/auth/2fa/enable
 * Enable 2FA after setup
 */
router.post(
  '/2fa/enable',
  authenticate,
  validators.totpCodeValidator,
  validate,
  authController.enable2FA
);

/**
 * POST /api/v1/auth/2fa/disable
 * Disable 2FA
 */
router.post(
  '/2fa/disable',
  authenticate,
  validators.totpCodeValidator,
  validate,
  authController.disable2FA
);

/**
 * POST /api/v1/auth/2fa/backup-codes
 * Regenerate backup codes
 */
router.post(
  '/2fa/backup-codes',
  authenticate,
  validators.totpCodeValidator,
  validate,
  authController.regenerateBackupCodes
);

// ============================================================================
// Account Linking
// ============================================================================

/**
 * GET /api/v1/auth/linked-accounts
 * Get linked OAuth accounts
 */
router.get('/linked-accounts', authenticate, authController.getLinkedAccounts);

/**
 * DELETE /api/v1/auth/linked-accounts/:provider
 * Unlink OAuth account
 */
router.delete(
  '/linked-accounts/:provider',
  authenticate,
  validators.oauthProviderValidator,
  validate,
  authController.unlinkAccount
);

// ============================================================================
// Current User
// ============================================================================

/**
 * GET /api/v1/auth/me
 * Get current authenticated user
 */
router.get('/me', authenticate, authController.getCurrentUser);

export { router as authRouter };
