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

class SuppliersController {
  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 as string,
        status: req.query.status as string,
        rating: req.query.rating ? parseInt(req.query.rating as string) : undefined,
        category: req.query.category as string,
      };

      const result = await suppliersService.findAll(filters, page, pageSize);
      res.json(ResponseFormatter.paginated(result.suppliers, result.total, result.page, result.pageSize));
    } catch (error) {
      next(error);
    }
  }

  async getStats(req: AuthRequest, res: Response, next: NextFunction) {
    try {
      const stats = await suppliersService.getStats();
      res.json(ResponseFormatter.success(stats));
    } catch (error) {
      next(error);
    }
  }

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

  async create(req: AuthRequest, res: Response, next: NextFunction) {
    try {
      const supplier = await suppliersService.create({ ...req.body, createdById: req.user!.id }, req.user!.id);
      res.status(201).json(ResponseFormatter.success(supplier, 'تم إنشاء المورد بنجاح - Supplier created successfully'));
    } catch (error) {
      next(error);
    }
  }

  async update(req: AuthRequest, res: Response, next: NextFunction) {
    try {
      const supplier = await suppliersService.update(req.params.id, req.body, req.user!.id);
      res.json(ResponseFormatter.success(supplier, 'تم تحديث المورد بنجاح - Supplier updated successfully'));
    } catch (error) {
      next(error);
    }
  }

  async archive(req: AuthRequest, res: Response, next: NextFunction) {
    try {
      const supplier = await suppliersService.archive(req.params.id, req.user!.id, req.body.reason);
      res.json(ResponseFormatter.success(supplier, 'تم أرشفة المورد بنجاح - Supplier archived successfully'));
    } catch (error) {
      next(error);
    }
  }

  async export(req: AuthRequest, res: Response, next: NextFunction) {
    try {
      const filters = {
        search: req.query.search as string,
        status: req.query.status as string,
        rating: req.query.rating ? parseInt(req.query.rating as string) : undefined,
        category: req.query.category as string,
      };

      const buffer = await suppliersService.export(filters);
      res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
      res.setHeader('Content-Disposition', `attachment; filename=suppliers-${Date.now()}.xlsx`);
      res.send(buffer);
    } catch (error) {
      next(error);
    }
  }
}

export const suppliersController = new SuppliersController();
