import { Request, Response } from 'express';
import { BillingService } from '../services/billingService';

class BillingController {
  private billingService: BillingService;

  constructor() {
    this.billingService = new BillingService();
  }

  public async manageSubscription(req: Request, res: Response): Promise<void> {
    try {
      const { userId } = req.body;
      const result = await this.billingService.getSubscription(userId);
      res.status(200).json(result);
    } catch (error) {
      res.status(500).json({ message: 'Error managing subscription', error });
    }
  }

  public async getPricingTiers(req: Request, res: Response): Promise<void> {
    try {
      const pricingTiers = await this.billingService.getPricingTiers();
      res.status(200).json(pricingTiers);
    } catch (error) {
      res.status(500).json({ message: 'Error fetching pricing tiers', error });
    }
  }

  public async applyCoupon(req: Request, res: Response): Promise<void> {
    try {
      const { couponCode } = req.body;
      const result = await this.billingService.applyCoupon(couponCode);
      res.status(200).json(result);
    } catch (error) {
      res.status(500).json({ message: 'Error applying coupon', error });
    }
  }

  public async processRefund(req: Request, res: Response): Promise<void> {
    try {
      const { transactionId } = req.body;
      const result = await this.billingService.processRefund(transactionId);
      res.status(200).json(result);
    } catch (error) {
      res.status(500).json({ message: 'Error processing refund', error });
    }
  }

  public async renewSubscription(req: Request, res: Response): Promise<void> {
    try {
      const { subscriptionId } = req.body;
      const result = await this.billingService.renewSubscription(subscriptionId);
      res.status(200).json(result);
    } catch (error) {
      res.status(500).json({ message: 'Error renewing subscription', error });
    }
  }

  public async overrideBilling(req: Request, res: Response): Promise<void> {
    try {
      const { userId, amount } = req.body;
      await this.billingService.overrideBilling(userId, amount);
      res.status(200).json({ message: 'Billing overridden successfully' });
    } catch (error) {
      res.status(500).json({ message: 'Error overriding billing', error });
    }
  }

  public async checkFeature(req: Request, res: Response): Promise<void> {
    try {
      const { userId, featureKey } = req.query;
      const hasAccess = await this.billingService.checkFeatureGating(userId as string, featureKey as string);
      res.status(200).json({ hasAccess });
    } catch (error) {
      res.status(500).json({ message: 'Error checking feature gating', error });
    }
  }
}

export default BillingController;