import { Request, Response, NextFunction, Router } from 'express';
import { PurchasesService } from '../services';

export class PurchasesController {
  public router: Router;
  constructor(private readonly purchasesService: PurchasesService) {
    this.router = Router();
    this.router.get('/', this.findAll.bind(this));
    this.router.get('/:id', this.findOne.bind(this));
    this.router.post('/', this.create.bind(this));
    this.router.patch('/:id', this.update.bind(this));
    this.router.delete('/:id', this.delete.bind(this));
    this.router.post('/:id/confirm', this.confirm.bind(this));
    this.router.post('/:id/receive', this.receive.bind(this));
  }

  private async findAll(req: Request, res: Response, next: NextFunction) {
    try {
      const tenantId = req.headers['x-tenant-id'] as string;
      if (!tenantId) { res.status(400).json({ error: 'Tenant ID required' }); return; }
      const { supplierId, status, buyerId, limit, offset } = req.query;
      const result = await this.purchasesService.findAll({ tenantId, supplierId: supplierId as string, status: status as string, buyerId: buyerId as string, limit: limit ? parseInt(limit as string) : undefined, offset: offset ? parseInt(offset as string) : undefined });
      res.json(result);
    } catch (e) { next(e); }
  }

  private async findOne(req: Request, res: Response, next: NextFunction) {
    try {
      const tenantId = req.headers['x-tenant-id'] as string;
      if (!tenantId) { res.status(400).json({ error: 'Tenant ID required' }); return; }
      const order = await this.purchasesService.findOne(req.params.id, tenantId);
      if (!order) { res.status(404).json({ error: 'Not found' }); return; }
      res.json({ data: order });
    } catch (e) { next(e); }
  }

  private async create(req: Request, res: Response, next: NextFunction) {
    try {
      const tenantId = req.headers['x-tenant-id'] as string;
      const userId = req.headers['x-user-id'] as string;
      if (!tenantId) { res.status(400).json({ error: 'Tenant ID required' }); return; }
      const order = await this.purchasesService.create(tenantId, req.body, userId);
      res.status(201).json({ data: order });
    } catch (e) { next(e); }
  }

  private async update(req: Request, res: Response, next: NextFunction) {
    try {
      const tenantId = req.headers['x-tenant-id'] as string;
      const userId = req.headers['x-user-id'] as string;
      if (!tenantId) { res.status(400).json({ error: 'Tenant ID required' }); return; }
      const order = await this.purchasesService.update(req.params.id, tenantId, req.body, userId);
      if (!order) { res.status(404).json({ error: 'Not found' }); return; }
      res.json({ data: order });
    } catch (e) { next(e); }
  }

  private async delete(req: Request, res: Response, next: NextFunction) {
    try {
      const tenantId = req.headers['x-tenant-id'] as string;
      if (!tenantId) { res.status(400).json({ error: 'Tenant ID required' }); return; }
      const deleted = await this.purchasesService.delete(req.params.id, tenantId);
      if (!deleted) { res.status(404).json({ error: 'Not found' }); return; }
      res.status(204).send();
    } catch (e) { next(e); }
  }

  private async confirm(req: Request, res: Response, next: NextFunction) {
    try {
      const tenantId = req.headers['x-tenant-id'] as string;
      const userId = req.headers['x-user-id'] as string;
      if (!tenantId) { res.status(400).json({ error: 'Tenant ID required' }); return; }
      const order = await this.purchasesService.confirmOrder(req.params.id, tenantId, userId);
      if (!order) { res.status(400).json({ error: 'Cannot confirm' }); return; }
      res.json({ data: order });
    } catch (e) { next(e); }
  }

  private async receive(req: Request, res: Response, next: NextFunction) {
    try {
      const tenantId = req.headers['x-tenant-id'] as string;
      const userId = req.headers['x-user-id'] as string;
      if (!tenantId) { res.status(400).json({ error: 'Tenant ID required' }); return; }
      const order = await this.purchasesService.receiveOrder(req.params.id, tenantId, userId);
      if (!order) { res.status(400).json({ error: 'Cannot receive' }); return; }
      res.json({ data: order });
    } catch (e) { next(e); }
  }
}
