import {
  BadRequestException,
  Controller,
  Get,
  Post,
  Patch,
  Delete,
  Param,
  Body,
  Query,
  ParseUUIDPipe,
  UploadedFiles,
  UseInterceptors,
} from '@nestjs/common';
import { AnyFilesInterceptor } from '@nestjs/platform-express';
import { ApiBearerAuth, ApiConsumes, ApiOperation, ApiTags } from '@nestjs/swagger';
import { BookingStaff } from '../../common/booking-guards';
import { FREIGHT_PERMS } from '../../seed/freight-permissions.registry';
import { DriversService } from './drivers.service';
import { CreateDriverDto } from './dto/create-driver.dto';
import { UpdateDriverDto } from './dto/update-driver.dto';
import { FleetHistoryService } from '../fleet-history/fleet-history.service';

@ApiTags('drivers')
@ApiBearerAuth()
@Controller('drivers')
@BookingStaff(FREIGHT_PERMS.drivers.view)
export class DriversController {
  constructor(
    private readonly driversService: DriversService,
    private readonly fleetHistory: FleetHistoryService,
  ) {}

  @Post()
  @BookingStaff(FREIGHT_PERMS.drivers.create)
  @ApiOperation({ summary: 'Create a new driver' })
  create(@Body() createDriverDto: CreateDriverDto) {
    return this.driversService.create(createDriverDto);
  }

  @Get()
  @ApiOperation({ summary: 'Get all drivers with filters' })
  findAll(
    @Query('search') search?: string,
    @Query('status') status?: string,
    @Query('page') page?: string,
    @Query('limit') limit?: string,
    @Query('sortBy') sortBy?: string,
    @Query('sortOrder') sortOrder?: 'ASC' | 'DESC',
  ) {
    return this.driversService.findAll({
      search,
      status: status as any,
      page: page ? parseInt(page) : undefined,
      limit: limit ? parseInt(limit) : undefined,
      sortBy,
      sortOrder,
    });
  }

  @Get(':id')
  @ApiOperation({ summary: 'Get driver by id' })
  findOne(@Param('id', ParseUUIDPipe) id: string) {
    return this.driversService.findById(id);
  }

  @Get(':id/history')
  @ApiOperation({ summary: 'Get driver assignment & activity history' })
  history(@Param('id', ParseUUIDPipe) id: string) {
    return this.fleetHistory.getDriverHistory(id);
  }

  @Post(':id/documents')
  @BookingStaff(FREIGHT_PERMS.drivers.update)
  @ApiConsumes('multipart/form-data')
  // Bound the upload: 10MB/file, max 20 files, images + PDF only. Without limits
  // AnyFilesInterceptor buffers arbitrarily large / arbitrary-type payloads.
  @UseInterceptors(
    AnyFilesInterceptor({
      limits: { fileSize: 10 * 1024 * 1024, files: 20 },
      fileFilter: (_req, file, cb) => {
        const allowed = [
          'image/jpeg',
          'image/png',
          'image/webp',
          'image/gif',
          'application/pdf',
        ];
        if (allowed.includes(file.mimetype)) {
          cb(null, true);
        } else {
          cb(
            new BadRequestException(`Unsupported file type: ${file.mimetype}`),
            false,
          );
        }
      },
    }),
  )
  @ApiOperation({ summary: 'Upload driver documents (code driver_docs)' })
  uploadDocuments(
    @Param('id', ParseUUIDPipe) id: string,
    @UploadedFiles() files: Express.Multer.File[],
  ) {
    return this.driversService.uploadDocuments(id, files ?? []);
  }

  @Get(':id/documents')
  @ApiOperation({ summary: "List a driver's documents" })
  listDocuments(@Param('id', ParseUUIDPipe) id: string) {
    return this.driversService.listDocuments(id);
  }

  @Delete(':id/documents/:fileId')
  @BookingStaff(FREIGHT_PERMS.drivers.update)
  @ApiOperation({ summary: 'Delete a driver document' })
  removeDocument(@Param('fileId', ParseUUIDPipe) fileId: string) {
    return this.driversService.removeDocument(fileId);
  }

  @Patch(':id')
  @BookingStaff(FREIGHT_PERMS.drivers.update)
  @ApiOperation({ summary: 'Update a driver' })
  update(
    @Param('id', ParseUUIDPipe) id: string,
    @Body() updateDriverDto: UpdateDriverDto,
  ) {
    return this.driversService.update(id, updateDriverDto);
  }

  @Delete(':id')
  @BookingStaff(FREIGHT_PERMS.drivers.delete)
  @ApiOperation({ summary: 'Delete a driver' })
  remove(@Param('id', ParseUUIDPipe) id: string) {
    return this.driversService.remove(id);
  }
}
