const express = require('express');
const router = express.Router();
const { authenticateUser, isValidDomain } = require('../middleware/auth');
const {
  generateDomainVerificationToken,
  verifyDomainOwnership,
  verifyAethexDomain,
  getVerificationStatus
} = require('../utils/domainVerification');

/**
 * POST /api/passport/domain/request-verification
 * Request domain verification token
 */
router.post('/request-verification', authenticateUser, async (req, res) => {
  try {
    const { domain } = req.body;
    
    // Validate input
    if (!domain) {
      return res.status(400).json({
        success: false,
        error: 'Domain is required'
      });
    }
    
    if (!isValidDomain(domain)) {
      return res.status(400).json({
        success: false,
        error: 'Invalid domain format. Please enter a valid domain (e.g., example.com or sub.example.com)'
      });
    }
    
    // Generate verification token
    const verification = await generateDomainVerificationToken(req.user.id, domain);
    
    res.json({
      success: true,
      verification: verification
    });
    
  } catch (error) {
    console.error('Request verification error:', error);
    res.status(500).json({
      success: false,
      error: 'Failed to generate verification token. Please try again.'
    });
  }
});

/**
 * POST /api/passport/domain/verify
 * Verify domain ownership via DNS or blockchain
 */
router.post('/verify', authenticateUser, async (req, res) => {
  try {
    const { domain, walletAddress } = req.body;
    
    // Validate input
    if (!domain) {
      return res.status(400).json({
        success: false,
        error: 'Domain is required'
      });
    }
    
    if (!isValidDomain(domain)) {
      return res.status(400).json({
        success: false,
        error: 'Invalid domain format'
      });
    }
    
    // Check if it's a .aethex domain (blockchain verification)
    let result;
    if (domain.endsWith('.aethex')) {
      if (!walletAddress) {
        return res.status(400).json({
          success: false,
          error: 'Wallet address is required for .aethex domain verification'
        });
      }
      
      result = await verifyAethexDomain(req.user.id, domain, walletAddress);
    } else {
      // DNS verification for traditional domains
      result = await verifyDomainOwnership(req.user.id, domain);
    }
    
    if (result.verified) {
      res.json({
        success: true,
        verified: true,
        domain: result.domain,
        verifiedAt: result.verifiedAt
      });
    } else {
      res.status(400).json({
        success: false,
        verified: false,
        error: result.error
      });
    }
    
  } catch (error) {
    console.error('Verify domain error:', error);
    res.status(500).json({
      success: false,
      verified: false,
      error: 'Verification failed. Please try again.'
    });
  }
});

/**
 * GET /api/passport/domain/status
 * Get current verification status for user
 */
router.get('/status', authenticateUser, async (req, res) => {
  try {
    const status = await getVerificationStatus(req.user.id);
    res.json(status);
  } catch (error) {
    console.error('Get status error:', error);
    res.status(500).json({
      success: false,
      error: 'Failed to get verification status'
    });
  }
});

module.exports = router;
