import { Request, Response, NextFunction } from 'express';
import { IDeviceRepository } from '../../domain/repositories/device-repository';

export const deviceValidationMiddleware = (deviceRepository: IDeviceRepository) => {
  return async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    const deviceId = req.headers['x-device-id'];

    if (typeof deviceId !== 'string' || !deviceId) {
      res.status(400).json({
        success: false,
        code: 'DEVICE_ID_REQUIRED',
        message: 'x-device-id header is required',
      });
      return;
    }

    const device = await deviceRepository.findById(deviceId);
    if (!device) {
      res.status(404).json({
        success: false,
        code: 'DEVICE_NOT_FOUND',
        message: 'Device not found',
      });
      return;
    }

    res.locals.deviceId = deviceId;
    next();
  };
};
