/**
 * Supplier Controller
 * Mecánicas Diesel - ERP Suite
 *
 * REST API endpoints for supplier management.
 */

import { Router, Request, Response, NextFunction } from 'express';
import { DataSource } from 'typeorm';
import { SupplierService } from '../services/supplier.service';

interface TenantRequest extends Request {
  tenantId?: string;
  userId?: string;
}

export function createSupplierController(dataSource: DataSource): Router {
  const router = Router();
  const service = new SupplierService(dataSource);

  const extractTenant = (req: TenantRequest, res: Response, next: NextFunction) => {
    const tenantId = req.headers['x-tenant-id'] as string;
    if (!tenantId) {
      return res.status(400).json({ error: 'Tenant ID is required' });
    }
    req.tenantId = tenantId;
    req.userId = req.headers['x-user-id'] as string;
    next();
  };

  router.use(extractTenant);

  /**
   * Create a new supplier
   * POST /api/suppliers
   */
  router.post('/', async (req: TenantRequest, res: Response) => {
    try {
      const supplier = await service.create(req.tenantId!, req.body);
      res.status(201).json(supplier);
    } catch (error) {
      res.status(400).json({ error: (error as Error).message });
    }
  });

  /**
   * List suppliers
   * GET /api/suppliers
   */
  router.get('/', async (req: TenantRequest, res: Response) => {
    try {
      const filters = {
        search: req.query.search as string,
        isActive: req.query.isActive === 'true' ? true : req.query.isActive === 'false' ? false : undefined,
      };

      const pagination = {
        page: parseInt(req.query.page as string, 10) || 1,
        limit: Math.min(parseInt(req.query.limit as string, 10) || 20, 100),
      };

      const result = await service.findAll(req.tenantId!, filters, pagination);
      res.json(result);
    } catch (error) {
      res.status(500).json({ error: (error as Error).message });
    }
  });

  /**
   * Search suppliers (for autocomplete)
   * GET /api/suppliers/search
   */
  router.get('/search', async (req: TenantRequest, res: Response) => {
    try {
      const query = req.query.q as string || '';
      const limit = Math.min(parseInt(req.query.limit as string, 10) || 10, 50);
      const suppliers = await service.search(req.tenantId!, query, limit);
      res.json(suppliers);
    } catch (error) {
      res.status(500).json({ error: (error as Error).message });
    }
  });

  /**
   * Get a single supplier
   * GET /api/suppliers/:id
   */
  router.get('/:id', async (req: TenantRequest, res: Response) => {
    try {
      const supplier = await service.findById(req.tenantId!, req.params.id);
      if (!supplier) {
        return res.status(404).json({ error: 'Supplier not found' });
      }
      res.json(supplier);
    } catch (error) {
      res.status(500).json({ error: (error as Error).message });
    }
  });

  /**
   * Get supplier with statistics
   * GET /api/suppliers/:id/stats
   */
  router.get('/:id/stats', async (req: TenantRequest, res: Response) => {
    try {
      const result = await service.getSupplierWithStats(req.tenantId!, req.params.id);
      if (!result) {
        return res.status(404).json({ error: 'Supplier not found' });
      }
      res.json(result);
    } catch (error) {
      res.status(500).json({ error: (error as Error).message });
    }
  });

  /**
   * Update supplier
   * PATCH /api/suppliers/:id
   */
  router.patch('/:id', async (req: TenantRequest, res: Response) => {
    try {
      const supplier = await service.update(req.tenantId!, req.params.id, req.body);
      if (!supplier) {
        return res.status(404).json({ error: 'Supplier not found' });
      }
      res.json(supplier);
    } catch (error) {
      res.status(400).json({ error: (error as Error).message });
    }
  });

  /**
   * Deactivate supplier
   * DELETE /api/suppliers/:id
   */
  router.delete('/:id', async (req: TenantRequest, res: Response) => {
    try {
      const success = await service.deactivate(req.tenantId!, req.params.id);
      if (!success) {
        return res.status(404).json({ error: 'Supplier not found' });
      }
      res.status(204).send();
    } catch (error) {
      res.status(500).json({ error: (error as Error).message });
    }
  });

  return router;
}
