const express = require('express');
const router = express.Router();
const { authenticateUser: auth } = require('../middleware/auth');
const premiumService = require('../services/premiumService');

/**
 * POST /api/premium/domains/check-availability
 * Check if a .aethex domain is available
 */
router.post('/domains/check-availability', auth, async (req, res) => {
  try {
    const { domain } = req.body;

    if (!domain) {
      return res.status(400).json({
        success: false,
        error: 'Domain is required'
      });
    }

    const result = await premiumService.checkDomainAvailability(domain);

    res.json({
      success: true,
      ...result
    });

  } catch (error) {
    console.error('Domain availability check failed:', error);
    res.status(400).json({
      success: false,
      error: error.message
    });
  }
});

/**
 * POST /api/premium/domains/register
 * Register a premium .aethex domain
 */
router.post('/domains/register', auth, async (req, res) => {
  try {
    const { domain, walletAddress, paymentMethodId } = req.body;
    const userId = req.user.id;

    if (!domain || !walletAddress || !paymentMethodId) {
      return res.status(400).json({
        success: false,
        error: 'Domain, wallet address, and payment method are required'
      });
    }

    const result = await premiumService.registerDomain(
      userId,
      domain,
      walletAddress,
      paymentMethodId
    );

    res.json({
      success: true,
      domain: {
        id: result.domain.id,
        domain: result.domain.domain,
        status: result.domain.verified ? 'verified' : 'pending_verification',
        nftMintTx: result.nftMintTx,
        verificationRequired: !result.domain.verified,
        expiresAt: result.domain.expires_at
      },
      subscription: {
        id: result.subscription.id,
        tier: result.subscription.tier,
        nextBillingDate: result.subscription.current_period_end,
        amount: 100.00
      }
    });

  } catch (error) {
    console.error('Domain registration failed:', error);
    res.status(400).json({
      success: false,
      error: error.message
    });
  }
});

/**
 * GET /api/premium/domains
 * Get user's premium domains
 */
router.get('/domains', auth, async (req, res) => {
  try {
    const userId = req.user.id;

    const domains = await premiumService.getUserDomains(userId);

    res.json({
      success: true,
      domains
    });

  } catch (error) {
    console.error('Failed to get domains:', error);
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

/**
 * POST /api/premium/subscribe
 * Subscribe to premium tier
 */
router.post('/subscribe', auth, async (req, res) => {
  try {
    const { tier, paymentMethodId, billingPeriod = 'yearly' } = req.body;
    const userId = req.user.id;

    if (!tier || !paymentMethodId) {
      return res.status(400).json({
        success: false,
        error: 'Tier and payment method are required'
      });
    }

    if (!['premium', 'enterprise'].includes(tier)) {
      return res.status(400).json({
        success: false,
        error: 'Invalid tier'
      });
    }

    const subscription = await premiumService.subscribe(
      userId,
      tier,
      paymentMethodId,
      billingPeriod
    );

    res.json({
      success: true,
      subscription: {
        id: subscription.id,
        tier: subscription.tier,
        status: subscription.status,
        currentPeriodEnd: subscription.current_period_end,
        amount: tier === 'premium' ? (billingPeriod === 'yearly' ? 100.00 : 10.00) : 500.00,
        interval: billingPeriod === 'yearly' ? 'year' : 'month'
      }
    });

  } catch (error) {
    console.error('Subscription failed:', error);
    res.status(400).json({
      success: false,
      error: error.message
    });
  }
});

/**
 * GET /api/premium/subscription
 * Get current subscription
 */
router.get('/subscription', auth, async (req, res) => {
  try {
    const userId = req.user.id;

    const subscription = await premiumService.getSubscription(userId);

    if (!subscription) {
      return res.json({
        success: true,
        subscription: null
      });
    }

    res.json({
      success: true,
      subscription
    });

  } catch (error) {
    console.error('Failed to get subscription:', error);
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

/**
 * POST /api/premium/cancel
 * Cancel subscription
 */
router.post('/cancel', auth, async (req, res) => {
  try {
    const { cancelAtPeriodEnd = true, reason } = req.body;
    const userId = req.user.id;

    const result = await premiumService.cancelSubscription(
      userId,
      cancelAtPeriodEnd
    );

    res.json({
      success: true,
      subscription: {
        status: cancelAtPeriodEnd ? 'active' : 'cancelled',
        cancelAtPeriodEnd: result.cancelAtPeriodEnd,
        currentPeriodEnd: result.currentPeriodEnd
      }
    });

  } catch (error) {
    console.error('Cancellation failed:', error);
    res.status(400).json({
      success: false,
      error: error.message
    });
  }
});

/**
 * POST /api/premium/marketplace/list
 * List domain for sale on marketplace
 */
router.post('/marketplace/list', auth, async (req, res) => {
  try {
    const { domainId, priceUSD } = req.body;
    const userId = req.user.id;

    if (!domainId || !priceUSD) {
      return res.status(400).json({
        success: false,
        error: 'Domain ID and price are required'
      });
    }

    if (priceUSD < 10 || priceUSD > 100000) {
      return res.status(400).json({
        success: false,
        error: 'Price must be between $10 and $100,000'
      });
    }

    const result = await premiumService.listDomainOnMarketplace(
      domainId,
      userId,
      priceUSD
    );

    res.json({
      success: true,
      listing: result
    });

  } catch (error) {
    console.error('Failed to list domain:', error);
    res.status(400).json({
      success: false,
      error: error.message
    });
  }
});

/**
 * POST /api/premium/marketplace/unlist
 * Remove domain from marketplace
 */
router.post('/marketplace/unlist', auth, async (req, res) => {
  try {
    const { domainId } = req.body;
    const userId = req.user.id;

    if (!domainId) {
      return res.status(400).json({
        success: false,
        error: 'Domain ID is required'
      });
    }

    await premiumService.unlistDomainFromMarketplace(domainId, userId);

    res.json({
      success: true
    });

  } catch (error) {
    console.error('Failed to unlist domain:', error);
    res.status(400).json({
      success: false,
      error: error.message
    });
  }
});

/**
 * GET /api/premium/marketplace
 * Browse marketplace listings
 */
router.get('/marketplace', async (req, res) => {
  try {
    const { sort = 'price_asc', limit = 20, page = 1 } = req.query;
    const offset = (page - 1) * limit;

    const listings = await premiumService.getMarketplaceListings(
      parseInt(limit),
      parseInt(offset),
      sort
    );

    res.json({
      success: true,
      listings,
      total: listings.length,
      page: parseInt(page)
    });

  } catch (error) {
    console.error('Failed to get marketplace listings:', error);
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

/**
 * GET /api/premium/analytics
 * Get usage analytics (premium/enterprise only)
 */
router.get('/analytics', auth, async (req, res) => {
  try {
    const userId = req.user.id;
    const { period = '30d' } = req.query;

    // Check if user has access to analytics
    const hasAccess = await premiumService.checkFeatureAccess(userId, 'analytics');

    if (!hasAccess) {
      return res.status(403).json({
        success: false,
        error: 'Analytics feature requires premium subscription'
      });
    }

    const analytics = await premiumService.getAnalytics(userId, period);

    res.json({
      success: true,
      ...analytics
    });

  } catch (error) {
    console.error('Failed to get analytics:', error);
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

/**
 * GET /api/premium/features
 * Get feature limits for user's tier
 */
router.get('/features', auth, async (req, res) => {
  try {
    const userId = req.user.id;

    const subscription = await premiumService.getSubscription(userId);

    res.json({
      success: true,
      tier: subscription?.tier || 'free',
      features: subscription?.features || {
        maxFriends: 5,
        storageGB: 0,
        voiceCalls: false,
        videoCalls: false,
        customBranding: false,
        analytics: false,
        prioritySupport: false
      }
    });

  } catch (error) {
    console.error('Failed to get features:', error);
    res.status(500).json({
      success: false,
      error: error.message
    });
  }
});

module.exports = router;
