import { Response, NextFunction } from 'express';
import { AuthRequest } from '../../shared/middleware/auth';
import { dealsService } from './deals.service';
import { quotesService } from './quotes.service';
import { pipelinesService } from './pipelines.service';
import { ResponseFormatter } from '../../shared/utils/responseFormatter';

export class PipelinesController {
  async findAll(req: AuthRequest, res: Response, next: NextFunction) {
    try {
      const structure = req.query.structure as string | undefined;
      const pipelines = await pipelinesService.findAll({ structure });
      res.json(ResponseFormatter.success(pipelines));
    } catch (error) {
      next(error);
    }
  }

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

export class DealsController {
  async create(req: AuthRequest, res: Response, next: NextFunction) {
    try {
      const expectedCloseDate = req.body.expectedCloseDate
        ? new Date(req.body.expectedCloseDate)
        : undefined;
      const data = {
        ...req.body,
        ownerId: req.body.ownerId || req.user!.id,
        fiscalYear: req.body.fiscalYear || new Date().getFullYear(),
        expectedCloseDate,
      };
      
      const deal = await dealsService.create(data, req.user!.id);
      
      res.status(201).json(
        ResponseFormatter.success(deal, 'تم إنشاء الصفقة بنجاح - Deal created successfully')
      );
    } catch (error) {
      next(error);
    }
  }

  async findAll(req: AuthRequest, res: Response, next: NextFunction) {
    try {
      const page = parseInt(req.query.page as string) || 1;
      const pageSize = parseInt(req.query.pageSize as string) || 20;
      
      const filters = {
        search: req.query.search,
        structure: req.query.structure,
        stage: req.query.stage,
        status: req.query.status,
        ownerId: req.query.ownerId,
        fiscalYear: req.query.fiscalYear,
      };
      
      const result = await dealsService.findAll(filters, page, pageSize);
      
      res.json(ResponseFormatter.paginated(
        result.deals,
        result.total,
        result.page,
        result.pageSize
      ));
    } catch (error) {
      next(error);
    }
  }

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

  async update(req: AuthRequest, res: Response, next: NextFunction) {
    try {
      const body = { ...req.body } as Record<string, unknown>;
      if (body.expectedCloseDate) body.expectedCloseDate = new Date(body.expectedCloseDate as string);
      if (body.actualCloseDate) body.actualCloseDate = new Date(body.actualCloseDate as string);
      const deal = await dealsService.update(
        req.params.id,
        body as any,
        req.user!.id
      );
      
      res.json(
        ResponseFormatter.success(deal, 'تم تحديث الصفقة بنجاح - Deal updated successfully')
      );
    } catch (error) {
      next(error);
    }
  }

  async updateStage(req: AuthRequest, res: Response, next: NextFunction) {
    try {
      const { stage } = req.body;
      const deal = await dealsService.updateStage(
        req.params.id,
        stage,
        req.user!.id
      );
      
      res.json(
        ResponseFormatter.success(deal, 'تم تحديث مرحلة الصفقة - Deal stage updated')
      );
    } catch (error) {
      next(error);
    }
  }

  async win(req: AuthRequest, res: Response, next: NextFunction) {
    try {
      const { actualValue, wonReason } = req.body;
      const deal = await dealsService.win(
        req.params.id,
        actualValue,
        wonReason,
        req.user!.id
      );
      
      res.json(
        ResponseFormatter.success(deal, '🎉 تم الفوز بالصفقة - Deal won successfully!')
      );
    } catch (error) {
      next(error);
    }
  }

  async lose(req: AuthRequest, res: Response, next: NextFunction) {
    try {
      const { lostReason } = req.body;
      const deal = await dealsService.lose(
        req.params.id,
        lostReason,
        req.user!.id
      );
      
      res.json(
        ResponseFormatter.success(deal, 'تم تسجيل خسارة الصفقة - Deal marked as lost')
      );
    } catch (error) {
      next(error);
    }
  }

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

export class QuotesController {
  async create(req: AuthRequest, res: Response, next: NextFunction) {
    try {
      const quote = await quotesService.create(req.body, req.user!.id);
      
      res.status(201).json(
        ResponseFormatter.success(quote, 'تم إنشاء عرض السعر بنجاح - Quote created successfully')
      );
    } catch (error) {
      next(error);
    }
  }

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

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

  async approve(req: AuthRequest, res: Response, next: NextFunction) {
    try {
      const quote = await quotesService.approve(
        req.params.id,
        req.user!.id,
        req.user!.id
      );
      
      res.json(
        ResponseFormatter.success(quote, 'تمت الموافقة على عرض السعر - Quote approved')
      );
    } catch (error) {
      next(error);
    }
  }

  async send(req: AuthRequest, res: Response, next: NextFunction) {
    try {
      const quote = await quotesService.markAsSent(req.params.id, req.user!.id);
      
      res.json(
        ResponseFormatter.success(quote, 'تم إرسال عرض السعر - Quote sent')
      );
    } catch (error) {
      next(error);
    }
  }
}

export const pipelinesController = new PipelinesController();
export const dealsController = new DealsController();
export const quotesController = new QuotesController();

