import { Controller, Post, Get, Body, Param, Query } from '@nestjs/common';
import { ApiBearerAuth, ApiTags, ApiOperation } from '@nestjs/swagger';
import { BookingStaff } from '../../common/booking-guards';
import { FREIGHT_PERMS } from '../../seed/freight-permissions.registry';
import { FuelService } from './fuel.service';
import { CreateFuelPurchaseDto } from './dto/create-fuel-purchase.dto';

// Stats feed the Financial Reports + Fleet Dashboard pages, so their viewers may
// read them without full fuel access.
const FUEL_STATS_PERMS = [
  FREIGHT_PERMS.fuel.view,
  FREIGHT_PERMS.fleetReports.view,
  FREIGHT_PERMS.fleetDashboard.view,
];

@ApiTags('Fuel Management')
@ApiBearerAuth()
@Controller('fuel')
export class FuelController {
  constructor(private readonly fuelService: FuelService) {}

  @Post('purchases')
  @BookingStaff(FREIGHT_PERMS.fuel.create)
  @ApiOperation({ summary: 'Record fuel purchase' })
  async recordFuelPurchase(@Body() dto: CreateFuelPurchaseDto) {
    return this.fuelService.recordFuelPurchase(dto);
  }

  @Get('purchases')
  @BookingStaff(FREIGHT_PERMS.fuel.view)
  @ApiOperation({ summary: 'Get all fuel purchases' })
  async getAllFuelPurchases() {
    return this.fuelService.getAllFuelPurchases();
  }

  @Get('purchases/:vehicleId')
  @BookingStaff(FREIGHT_PERMS.fuel.view)
  @ApiOperation({ summary: 'Get fuel purchases for vehicle' })
  async getFuelPurchases(
    @Param('vehicleId') vehicleId: string,
    @Query('startDate') startDate: string,
    @Query('endDate') endDate: string,
  ) {
    return this.fuelService.getFuelPurchases(
      vehicleId,
      new Date(startDate),
      new Date(endDate),
    );
  }

  @Get('consumption/:vehicleId/:month')
  @BookingStaff(FREIGHT_PERMS.fuel.view)
  @ApiOperation({ summary: 'Get monthly fuel consumption' })
  async getMonthlyConsumption(
    @Param('vehicleId') vehicleId: string,
    @Param('month') month: string,
  ) {
    return this.fuelService.getMonthlyConsumption(vehicleId, new Date(month));
  }

  @Get('stats')
  @BookingStaff(FUEL_STATS_PERMS)
  @ApiOperation({ summary: 'Get fleet-wide fuel statistics' })
  async getFleetFuelStats(@Query('months') months: number = 12) {
    return this.fuelService.getFleetFuelStats(months);
  }

  @Get('stats/:vehicleId')
  @BookingStaff(FUEL_STATS_PERMS)
  @ApiOperation({ summary: 'Get fuel statistics for vehicle' })
  async getVehicleFuelStats(
    @Param('vehicleId') vehicleId: string,
    @Query('months') months: number = 12,
  ) {
    return this.fuelService.getVehicleFuelStats(vehicleId, months);
  }
}
