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

export class ContractsController {
  async create(req: AuthRequest, res: Response, next: NextFunction) {
    try {
      const contract = await contractsService.create(req.body, req.user!.id);
      res.status(201).json(
        ResponseFormatter.success(contract, 'تم إنشاء العقد - Contract created')
      );
    } catch (error) {
      next(error);
    }
  }

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

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

  async update(req: AuthRequest, res: Response, next: NextFunction) {
    try {
      const contract = await contractsService.update(req.params.id, req.body, req.user!.id);
      res.json(ResponseFormatter.success(contract, 'تم تحديث العقد - Contract updated'));
    } catch (error) {
      next(error);
    }
  }

  async updateStatus(req: AuthRequest, res: Response, next: NextFunction) {
    try {
      const { status } = req.body;
      const contract = await contractsService.updateStatus(req.params.id, status, req.user!.id);
      res.json(ResponseFormatter.success(contract, 'تم تحديث حالة العقد - Contract status updated'));
    } catch (error) {
      next(error);
    }
  }

  async markSigned(req: AuthRequest, res: Response, next: NextFunction) {
    try {
      const contract = await contractsService.markSigned(req.params.id, req.user!.id);
      res.json(ResponseFormatter.success(contract, 'تم توقيع العقد - Contract signed'));
    } catch (error) {
      next(error);
    }
  }
}

export const contractsController = new ContractsController();
