// Public IRU marketplace routes only (no inquiry/offering admin services) — safe for focused HTTP tests.

import { Router } from 'express';
import { marketplaceService } from '@/core/iru/marketplace.service';
import { validateRequest, iruValidationSchemas } from '@/integration/api-gateway/middleware/validation.middleware';
import {
  createIruMarketplaceInquiryPostLimiter,
  createIruMarketplacePublicReadLimiter,
} from '@/integration/api-gateway/middleware/rate-limit.middleware';
import type { InquiryRequest } from '@/core/iru/marketplace.service';

const router = Router();
const iruInquiryPostLimiter = createIruMarketplaceInquiryPostLimiter();
const iruPublicReadLimiter = createIruMarketplacePublicReadLimiter();

router.get('/offerings', iruPublicReadLimiter, async (req, res, next) => {
  try {
    const filters: Record<string, unknown> = {};
    if (req.query.capacityTier) {
      filters.capacityTier = parseInt(req.query.capacityTier as string, 10);
    }
    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 as Parameters<typeof marketplaceService.getOfferings>[0]
    );
    res.json({
      success: true,
      data: offerings,
      timestamp: new Date(),
    });
  } catch (error) {
    return next(error);
  }
});

router.get('/offerings/:offeringId/pricing', iruPublicReadLimiter, async (req, res, next) => {
  try {
    const { offeringId } = req.params;
    let usageProfile: unknown;
    if (req.query.usageProfile != null && String(req.query.usageProfile).trim() !== '') {
      try {
        usageProfile = JSON.parse(req.query.usageProfile as string);
      } catch {
        return res.status(400).json({
          success: false,
          error: {
            code: 'INVALID_JSON',
            message: 'usageProfile query parameter must be valid JSON',
          },
          timestamp: new Date(),
        });
      }
    }
    const pricing = await marketplaceService.calculatePricing(offeringId, usageProfile);
    res.json({
      success: true,
      data: pricing,
      timestamp: new Date(),
    });
  } catch (error) {
    return next(error);
  }
});

router.get('/offerings/:offeringId', iruPublicReadLimiter, 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);
  }
});

router.post(
  '/inquiries',
  iruInquiryPostLimiter,
  validateRequest({ body: iruValidationSchemas.inquiryRequest }),
  async (req, res, next) => {
    try {
      const result = await marketplaceService.submitInquiry(req.body as InquiryRequest);
      res.status(201).json({
        success: true,
        data: result,
        timestamp: new Date(),
      });
    } catch (error) {
      return next(error);
    }
  }
);

router.get('/inquiries/:inquiryId', iruPublicReadLimiter, async (req, res, next) => {
  try {
    const { inquiryId } = req.params;
    const inquiry = await marketplaceService.getInquiryStatusPublic(inquiryId);
    res.json({
      success: true,
      data: inquiry,
      timestamp: new Date(),
    });
  } catch (error) {
    return next(error);
  }
});

export default router;
