import { Response, NextFunction } from 'express';
import { AuthRequest } from '../../shared/middleware/auth';
import { invoicesService } from './invoices.service';
import { ResponseFormatter } from '../../shared/utils/responseFormatter';

export class InvoicesController {
  async create(req: AuthRequest, res: Response, next: NextFunction) {
    try {
      const invoice = await invoicesService.create(req.body, req.user!.id);
      res.status(201).json(
        ResponseFormatter.success(invoice, 'تم إنشاء الفاتورة - Invoice created')
      );
    } catch (error) {
      next(error);
    }
  }

  async findById(req: AuthRequest, res: Response, next: NextFunction) {
    try {
      const invoice = await invoicesService.findById(req.params.id);
      res.json(ResponseFormatter.success(invoice));
    } catch (error) {
      next(error);
    }
  }

  async findByDeal(req: AuthRequest, res: Response, next: NextFunction) {
    try {
      const list = await invoicesService.findByDeal(req.params.dealId);
      res.json(ResponseFormatter.success(list));
    } catch (error) {
      next(error);
    }
  }

  async update(req: AuthRequest, res: Response, next: NextFunction) {
    try {
      const invoice = await invoicesService.update(req.params.id, req.body, req.user!.id);
      res.json(ResponseFormatter.success(invoice, 'تم تحديث الفاتورة - Invoice updated'));
    } catch (error) {
      next(error);
    }
  }

  async recordPayment(req: AuthRequest, res: Response, next: NextFunction) {
    try {
      const { paidAmount, paidDate } = req.body;
      const invoice = await invoicesService.recordPayment(
        req.params.id,
        paidAmount,
        paidDate ? new Date(paidDate) : new Date(),
        req.user!.id
      );
      res.json(ResponseFormatter.success(invoice, 'تم تسجيل الدفع - Payment recorded'));
    } catch (error) {
      next(error);
    }
  }
}

export const invoicesController = new InvoicesController();
