// IRU Marketplace API Routes
// Routes for Sankofa Phoenix Marketplace

import { Router } from 'express';
import { marketplaceService } from '@/core/iru/marketplace.service';
import { offeringService } from '@/core/iru/offering.service';
import { inquiryService } from '@/core/iru/inquiry.service';
import { zeroTrustAuthMiddleware } from '@/integration/api-gateway/middleware/auth.middleware';
import { adminPermissionMiddleware } from '@/integration/api-gateway/middleware/admin-permission.middleware';
import { validateRequest, iruValidationSchemas } from '@/integration/api-gateway/middleware/validation.middleware';

const router = Router();

// ============================================================================
// Public Marketplace Routes (No Auth Required)
// ============================================================================

/**
 * @route GET /api/v1/iru/marketplace/offerings
 * @desc Get all active IRU offerings
 * @access Public
 */
router.get('/offerings', async (req, res, next) => {
  try {
    const filters: any = {};
    if (req.query.capacityTier) {
      filters.capacityTier = parseInt(req.query.capacityTier as string);
    }
    if (req.query.institutionalType) {
      filters.institutionalType = req.query.institutionalType as string;
    }
    if (req.query.status) {
      filters.status = req.query.status as string;
    }

    const offerings = await marketplaceService.getOfferings(filters);
    res.json({
      success: true,
      data: offerings,
      timestamp: new Date(),
    });
  } catch (error) {
    return next(error);
  }
});

/**
 * @route GET /api/v1/iru/marketplace/offerings/:offeringId
 * @desc Get offering by ID
 * @access Public
 */
router.get('/offerings/:offeringId', async (req, res, next) => {
  try {
    const { offeringId } = req.params;
    const offering = await marketplaceService.getOfferingById(offeringId);

    if (!offering) {
      return res.status(404).json({
        success: false,
        error: {
          code: 'NOT_FOUND',
          message: `Offering ${offeringId} not found`,
        },
        timestamp: new Date(),
      });
    }

    res.json({
      success: true,
      data: offering,
      timestamp: new Date(),
    });
  } catch (error) {
    return next(error);
  }
});

/**
 * @route POST /api/v1/iru/marketplace/inquiries
 * @desc Submit initial inquiry
 * @access Public
 */
router.post(
  '/inquiries',
  validateRequest({ body: iruValidationSchemas.inquiryRequest }),
  async (req, res, next) => {
    try {
      const result = await marketplaceService.submitInquiry(req.body);
      res.status(201).json({
        success: true,
        data: result,
        timestamp: new Date(),
      });
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/v1/iru/marketplace/inquiries/:inquiryId
 * @desc Get inquiry status
 * @access Public (with inquiry ID)
 */
router.get('/inquiries/:inquiryId', async (req, res, next) => {
  try {
    const { inquiryId } = req.params;
    const inquiry = await marketplaceService.getInquiryStatus(inquiryId);
    res.json({
      success: true,
      data: inquiry,
      timestamp: new Date(),
    });
  } catch (error) {
    return next(error);
  }
});

/**
 * @route GET /api/v1/iru/marketplace/offerings/:offeringId/pricing
 * @desc Calculate pricing for an offering
 * @access Public
 */
router.get('/offerings/:offeringId/pricing', async (req, res, next) => {
  try {
    const { offeringId } = req.params;
    const usageProfile = req.query.usageProfile
      ? JSON.parse(req.query.usageProfile as string)
      : undefined;
    const pricing = await marketplaceService.calculatePricing(offeringId, usageProfile);
    res.json({
      success: true,
      data: pricing,
      timestamp: new Date(),
    });
  } catch (error) {
    return next(error);
  }
});

// ============================================================================
// Admin Routes (Auth Required)
// ============================================================================

/**
 * @route POST /api/v1/iru/marketplace/admin/offerings
 * @desc Create new IRU offering
 * @access Admin
 */
router.post(
  '/admin/offerings',
  zeroTrustAuthMiddleware,
  adminPermissionMiddleware,
  async (req, res, next) => {
    try {
      const offering = await offeringService.createOffering(req.body);
      res.status(201).json({
        success: true,
        data: offering,
        timestamp: new Date(),
      });
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route PUT /api/v1/iru/marketplace/admin/offerings/:offeringId
 * @desc Update IRU offering
 * @access Admin
 */
router.put(
  '/admin/offerings/:offeringId',
  zeroTrustAuthMiddleware,
  adminPermissionMiddleware,
  async (req, res, next) => {
    try {
      const { offeringId } = req.params;
      const offering = await offeringService.updateOffering(offeringId, req.body);
      res.json({
        success: true,
        data: offering,
        timestamp: new Date(),
      });
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route DELETE /api/v1/iru/marketplace/admin/offerings/:offeringId
 * @desc Delete IRU offering
 * @access Admin
 */
router.delete(
  '/admin/offerings/:offeringId',
  zeroTrustAuthMiddleware,
  adminPermissionMiddleware,
  async (req, res, next) => {
    try {
      const { offeringId } = req.params;
      await offeringService.deleteOffering(offeringId);
      res.json({
        success: true,
        message: `Offering ${offeringId} deleted successfully`,
        timestamp: new Date(),
      });
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/v1/iru/marketplace/admin/offerings/:offeringId/stats
 * @desc Get offering statistics
 * @access Admin
 */
router.get(
  '/admin/offerings/:offeringId/stats',
  zeroTrustAuthMiddleware,
  adminPermissionMiddleware,
  async (req, res, next) => {
    try {
      const { offeringId } = req.params;
      const stats = await offeringService.getOfferingStats(offeringId);
      res.json({
        success: true,
        data: stats,
        timestamp: new Date(),
      });
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/v1/iru/marketplace/admin/inquiries
 * @desc Get all inquiries with filters
 * @access Admin
 */
router.get(
  '/admin/inquiries',
  zeroTrustAuthMiddleware,
  adminPermissionMiddleware,
  async (req, res, next) => {
    try {
      const filters: any = {};
      if (req.query.status) {
        filters.status = req.query.status as string;
      }
      if (req.query.offeringId) {
        filters.offeringId = req.query.offeringId as string;
      }
      if (req.query.capacityTier) {
        filters.capacityTier = parseInt(req.query.capacityTier as string);
      }
      if (req.query.limit) {
        filters.limit = parseInt(req.query.limit as string);
      }
      if (req.query.offset) {
        filters.offset = parseInt(req.query.offset as string);
      }

      const inquiries = await inquiryService.getInquiries(filters);
      res.json({
        success: true,
        data: inquiries,
        timestamp: new Date(),
      });
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route GET /api/v1/iru/marketplace/admin/inquiries/:inquiryId
 * @desc Get inquiry by ID with full details
 * @access Admin
 */
router.get(
  '/admin/inquiries/:inquiryId',
  zeroTrustAuthMiddleware,
  adminPermissionMiddleware,
  async (req, res, next) => {
    try {
      const { inquiryId } = req.params;
      const inquiry = await inquiryService.getInquiryById(inquiryId);
      res.json({
        success: true,
        data: inquiry,
        timestamp: new Date(),
      });
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route POST /api/v1/iru/marketplace/admin/inquiries/:inquiryId/acknowledge
 * @desc Acknowledge inquiry
 * @access Admin
 */
router.post(
  '/admin/inquiries/:inquiryId/acknowledge',
  zeroTrustAuthMiddleware,
  adminPermissionMiddleware,
  async (req, res, next) => {
    try {
      const { inquiryId } = req.params;
      const result = await inquiryService.acknowledgeInquiry(inquiryId);
      res.json({
        success: true,
        data: result,
        timestamp: new Date(),
      });
    } catch (error) {
      return next(error);
    }
  }
);

/**
 * @route PUT /api/v1/iru/marketplace/admin/inquiries/:inquiryId
 * @desc Update inquiry
 * @access Admin
 */
router.put(
  '/admin/inquiries/:inquiryId',
  zeroTrustAuthMiddleware,
  adminPermissionMiddleware,
  async (req, res, next) => {
    try {
      const { inquiryId } = req.params;
      const result = await inquiryService.updateInquiry(inquiryId, req.body);
      res.json({
        success: true,
        data: result,
        timestamp: new Date(),
      });
    } catch (error) {
      return next(error);
    }
  }
);

export default router;
