/**
 * Diagnostic Controller
 * Mecánicas Diesel - ERP Suite
 *
 * REST API endpoints for vehicle diagnostics.
 */

import { Router, Request, Response, NextFunction } from 'express';
import { DataSource } from 'typeorm';
import { DiagnosticService } from '../services/diagnostic.service';
import { DiagnosticType, DiagnosticResult } from '../entities/diagnostic.entity';

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

export function createDiagnosticController(dataSource: DataSource): Router {
  const router = Router();
  const service = new DiagnosticService(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 diagnostic
   * POST /api/diagnostics
   */
  router.post('/', async (req: TenantRequest, res: Response) => {
    try {
      const diagnostic = await service.create(req.tenantId!, req.body);
      res.status(201).json(diagnostic);
    } catch (error) {
      res.status(400).json({ error: (error as Error).message });
    }
  });

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

  /**
   * Get diagnostics by vehicle
   * GET /api/diagnostics/vehicle/:vehicleId
   */
  router.get('/vehicle/:vehicleId', async (req: TenantRequest, res: Response) => {
    try {
      const diagnostics = await service.findByVehicle(req.tenantId!, req.params.vehicleId);
      res.json(diagnostics);
    } catch (error) {
      res.status(500).json({ error: (error as Error).message });
    }
  });

  /**
   * Get diagnostics by order
   * GET /api/diagnostics/order/:orderId
   */
  router.get('/order/:orderId', async (req: TenantRequest, res: Response) => {
    try {
      const diagnostics = await service.findByOrder(req.tenantId!, req.params.orderId);
      res.json(diagnostics);
    } catch (error) {
      res.status(500).json({ error: (error as Error).message });
    }
  });

  /**
   * Get vehicle diagnostic statistics
   * GET /api/diagnostics/vehicle/:vehicleId/stats
   */
  router.get('/vehicle/:vehicleId/stats', async (req: TenantRequest, res: Response) => {
    try {
      const stats = await service.getVehicleStats(req.tenantId!, req.params.vehicleId);
      res.json(stats);
    } catch (error) {
      res.status(500).json({ error: (error as Error).message });
    }
  });

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

  /**
   * Parse DTC codes from raw data
   * POST /api/diagnostics/parse-dtc
   */
  router.post('/parse-dtc', async (req: TenantRequest, res: Response) => {
    try {
      const items = service.parseDTCCodes(req.body.rawData || {});
      res.json(items);
    } catch (error) {
      res.status(400).json({ error: (error as Error).message });
    }
  });

  /**
   * Analyze injector test results
   * POST /api/diagnostics/analyze-injectors
   */
  router.post('/analyze-injectors', async (req: TenantRequest, res: Response) => {
    try {
      const items = service.analyzeInjectorTest(req.body.rawData || {});
      res.json(items);
    } catch (error) {
      res.status(400).json({ error: (error as Error).message });
    }
  });

  return router;
}
