/**
 * @ai-summary Fastify route handlers for fuel logs API
 * @ai-context HTTP request/response handling with Fastify reply methods
 */

import { FastifyRequest, FastifyReply } from 'fastify';
import { FuelLogsService } from '../domain/fuel-logs.service';
import { FuelLogsRepository } from '../data/fuel-logs.repository';
import { pool } from '../../../core/config/database';
import { logger } from '../../../core/logging/logger';
import { FuelLogParams, VehicleParams, EnhancedCreateFuelLogRequest, EnhancedUpdateFuelLogRequest } from '../domain/fuel-logs.types';

export class FuelLogsController {
  private fuelLogsService: FuelLogsService;

  constructor() {
    const repository = new FuelLogsRepository(pool);
    this.fuelLogsService = new FuelLogsService(repository);
  }
  
  async createFuelLog(request: FastifyRequest<{ Body: EnhancedCreateFuelLogRequest }>, reply: FastifyReply) {
    try {
      const userId = (request as any).user.sub;
      const fuelLog = await this.fuelLogsService.createFuelLog(request.body, userId);
      
      return reply.code(201).send(fuelLog);
    } catch (error: any) {
      logger.error('Error creating fuel log', { error, userId: (request as any).user?.sub });
      
      if (error.message.includes('not found')) {
        return reply.code(404).send({
          error: 'Not Found',
          message: error.message
        });
      }
      if (error.message.includes('Unauthorized')) {
        return reply.code(403).send({
          error: 'Forbidden',
          message: error.message
        });
      }
      
      return reply.code(500).send({
        error: 'Internal server error',
        message: 'Failed to create fuel log'
      });
    }
  }
  
  async getFuelLogsByVehicle(request: FastifyRequest<{ Params: VehicleParams }>, reply: FastifyReply) {
    try {
      const userId = (request as any).user.sub;
      const { vehicleId } = request.params;
      
      const fuelLogs = await this.fuelLogsService.getFuelLogsByVehicle(vehicleId, userId);
      
      return reply.code(200).send(fuelLogs);
    } catch (error: any) {
      logger.error('Error listing fuel logs', { error, vehicleId: request.params.vehicleId, userId: (request as any).user?.sub });
      
      if (error.message.includes('not found')) {
        return reply.code(404).send({
          error: 'Not Found',
          message: error.message
        });
      }
      if (error.message.includes('Unauthorized')) {
        return reply.code(403).send({
          error: 'Forbidden',
          message: error.message
        });
      }
      
      return reply.code(500).send({
        error: 'Internal server error',
        message: 'Failed to get fuel logs'
      });
    }
  }
  
  async getUserFuelLogs(request: FastifyRequest, reply: FastifyReply) {
    try {
      const userId = (request as any).user.sub;
      const fuelLogs = await this.fuelLogsService.getUserFuelLogs(userId);
      
      return reply.code(200).send(fuelLogs);
    } catch (error: any) {
      logger.error('Error listing all fuel logs', { error, userId: (request as any).user?.sub });
      return reply.code(500).send({
        error: 'Internal server error',
        message: 'Failed to get fuel logs'
      });
    }
  }
  
  async getFuelLog(request: FastifyRequest<{ Params: FuelLogParams }>, reply: FastifyReply) {
    try {
      const userId = (request as any).user.sub;
      const { id } = request.params;
      
      const fuelLog = await this.fuelLogsService.getFuelLog(id, userId);
      
      return reply.code(200).send(fuelLog);
    } catch (error: any) {
      logger.error('Error getting fuel log', { error, fuelLogId: request.params.id, userId: (request as any).user?.sub });
      
      if (error.message === 'Fuel log not found') {
        return reply.code(404).send({
          error: 'Not Found',
          message: error.message
        });
      }
      if (error.message === 'Unauthorized') {
        return reply.code(403).send({
          error: 'Forbidden',
          message: error.message
        });
      }
      
      return reply.code(500).send({
        error: 'Internal server error',
        message: 'Failed to get fuel log'
      });
    }
  }
  
  async updateFuelLog(request: FastifyRequest<{ Params: FuelLogParams; Body: EnhancedUpdateFuelLogRequest }>, reply: FastifyReply) {
    try {
      const userId = (request as any).user.sub;
      const { id } = request.params;

      const updatedFuelLog = await this.fuelLogsService.updateFuelLog(id, request.body, userId);

      return reply.code(200).send(updatedFuelLog);
    } catch (error: any) {
      logger.error('Error updating fuel log', { error, fuelLogId: request.params.id, userId: (request as any).user?.sub });

      if (error.message.includes('not found')) {
        return reply.code(404).send({
          error: 'Not Found',
          message: error.message
        });
      }
      if (error.message === 'Unauthorized') {
        return reply.code(403).send({
          error: 'Forbidden',
          message: error.message
        });
      }
      if (error.message.includes('No fields provided')) {
        return reply.code(400).send({
          error: 'Bad Request',
          message: error.message
        });
      }

      return reply.code(500).send({
        error: 'Internal server error',
        message: 'Failed to update fuel log'
      });
    }
  }
  
  async deleteFuelLog(request: FastifyRequest<{ Params: FuelLogParams }>, reply: FastifyReply) {
    try {
      const userId = (request as any).user.sub;
      const { id } = request.params;
      
      await this.fuelLogsService.deleteFuelLog(id, userId);
      
      return reply.code(204).send();
    } catch (error: any) {
      logger.error('Error deleting fuel log', { error, fuelLogId: request.params.id, userId: (request as any).user?.sub });
      
      if (error.message.includes('not found')) {
        return reply.code(404).send({
          error: 'Not Found',
          message: error.message
        });
      }
      if (error.message === 'Unauthorized') {
        return reply.code(403).send({
          error: 'Forbidden',
          message: error.message
        });
      }
      
      return reply.code(500).send({
        error: 'Internal server error',
        message: 'Failed to delete fuel log'
      });
    }
  }
  
  async getFuelStats(request: FastifyRequest<{ Params: VehicleParams }>, reply: FastifyReply) {
    try {
      const userId = (request as any).user.sub;
      const { vehicleId } = request.params;
      
      const stats = await this.fuelLogsService.getVehicleStats(vehicleId, userId);
      
      return reply.code(200).send(stats);
    } catch (error: any) {
      logger.error('Error getting fuel stats', { error, vehicleId: request.params.vehicleId, userId: (request as any).user?.sub });
      
      if (error.message.includes('not found')) {
        return reply.code(404).send({
          error: 'Not Found',
          message: error.message
        });
      }
      if (error.message === 'Unauthorized') {
        return reply.code(403).send({
          error: 'Forbidden',
          message: error.message
        });
      }
      
      return reply.code(500).send({
        error: 'Internal server error',
        message: 'Failed to get fuel stats'
      });
    }
  }
}
