import { Request, Response } from 'express';
import { BillingService } from '../../domains/Billing/BillingService';
import { logger } from '../../utils/logger';

/**
 * [BIZ_BILL_01] 企业配额与计费控制器
 */
export class BillingController {
  /**
   * 订阅套餐并激活配额
   * POST /api/v1/billing/subscribe
   */
  static async subscribe(req: Request, res: Response) {
    const { tenantId, planId } = req.body;

    if (!tenantId || !planId) {
      return res.status(400).json({ success: false, error: 'tenantId and planId are required' });
    }

    try {
      await BillingService.subscribe(tenantId, planId);
      logger.info(`[BillingController] Tenant ${tenantId} subscribed to plan ${planId}`);
      
      return res.json({
        success: true,
        data: {
          tenantId,
          planId
        }
      });
    } catch (err: any) {
      logger.error(`[BillingController] Subscribe failed: ${err.message}`);
      return res.status(err.message.includes('not found') ? 404 : 500).json({ 
        success: false, 
        error: err.message || 'Internal server error' 
      });
    }
  }

  /**
   * 获取当前租户的配额用量
   * GET /api/v1/billing/usage
   */
  static async getUsage(req: Request, res: Response) {
    const tenantId = req.headers['x-tenant-id'] as string || req.query.tenantId as string;

    if (!tenantId) {
      return res.status(400).json({ success: false, error: 'tenantId is required in headers or query' });
    }

    try {
      const usage = await BillingService.getUsage(tenantId);
      if (!usage) {
        return res.status(404).json({ success: false, error: 'No quota record found for this tenant' });
      }

      return res.json({
        success: true,
        data: usage
      });
    } catch (err: any) {
      logger.error(`[BillingController] Get usage failed: ${err.message}`);
      return res.status(500).json({ success: false, error: 'Internal server error' });
    }
  }
}

