import {
  Controller,
  Get,
  Post,
  Patch,
  Delete,
  Body,
  Param,
  Query,
  UseGuards,
  ParseUUIDPipe,
  Res,
  UploadedFile,
  UseInterceptors,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { Response } from 'express';
import { TransportPricingService } from './transport-pricing.service';
import { CreateTransportPricingDto, UpdateTransportPricingDto } from './dto';
import { JwtAuthGuard } from '../../auth/guards/jwt-auth.guard';
import { PermissionGuard } from '../../auth/guards/permission.guard';
import { Permissions } from '../../auth/decorators/permissions.decorator';
import { AccessLevel, ModuleName } from '../../entities/role-permission.entity';
import { successResponse, paginatedResponse } from '../../common/responses/api-response';

@Controller('transport-pricing')
@UseGuards(JwtAuthGuard, PermissionGuard)
export class TransportPricingController {
  constructor(private readonly service: TransportPricingService) {}

  @Get()
  @Permissions({ module: ModuleName.TRANSPORT_PRICING, accessLevel: AccessLevel.VIEW })
  async findPaginated(
    @Query('destination_id') destinationId?: string,
    @Query('currency_id') currencyId?: string,
    @Query('search') search?: string,
    @Query('page') page?: string,
    @Query('limit') limit?: string,
  ) {
    const { items, meta } = await this.service.findPaginated({
      destinationId,
      currencyId,
      search,
      page: page ? parseInt(page) : 1,
      limit: limit ? parseInt(limit) : 10,
    });
    return paginatedResponse(items, meta, 'Transport pricing fetched successfully');
  }

  @Get('sample')
  @Permissions({ module: ModuleName.TRANSPORT_PRICING, accessLevel: AccessLevel.VIEW })
  async downloadSample(
    @Res() res: Response,
    @Query('destination_id') destinationId?: string,
  ) {
    const buffer = await this.service.generateSample(destinationId);
    res.setHeader(
      'Content-Type',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    );
    res.setHeader('Content-Disposition', 'attachment; filename="transport-pricing-sample.xlsx"');
    res.send(buffer);
  }

  @Post('import')
  @Permissions({ module: ModuleName.TRANSPORT_PRICING, accessLevel: AccessLevel.EDIT })
  @UseInterceptors(FileInterceptor('file', { limits: { fileSize: 10 * 1024 * 1024 } }))
  async importExcel(@UploadedFile() file: Express.Multer.File) {
    const result = await this.service.importFromExcel(file.buffer);
    return successResponse(result, result.message);
  }

  @Get('vehicle-types')
  @Permissions({ module: ModuleName.TRANSPORT_PRICING, accessLevel: AccessLevel.VIEW })
  async getVehicleTypes(@Query('destination_id') destinationId: string) {
    const data = await this.service.getVehicleTypes(destinationId);
    return successResponse(data, 'Vehicle types fetched successfully');
  }

  @Get(':id')
  @Permissions({ module: ModuleName.TRANSPORT_PRICING, accessLevel: AccessLevel.VIEW })
  async findById(@Param('id', ParseUUIDPipe) id: string) {
    const data = await this.service.findById(id);
    return successResponse(data, 'Transport pricing fetched successfully');
  }

  @Post()
  @Permissions({ module: ModuleName.TRANSPORT_PRICING, accessLevel: AccessLevel.CREATE })
  async create(@Body() dto: CreateTransportPricingDto) {
    const result = await this.service.create(dto);
    return successResponse(result, result.message);
  }

  @Post('bulk')
  @Permissions({ module: ModuleName.TRANSPORT_PRICING, accessLevel: AccessLevel.CREATE })
  async bulkSave(@Body() body: { items: CreateTransportPricingDto[] }) {
    const result = await this.service.bulkSave(body.items);
    return successResponse(result, result.message);
  }

  @Patch(':id')
  @Permissions({ module: ModuleName.TRANSPORT_PRICING, accessLevel: AccessLevel.EDIT })
  async update(@Param('id', ParseUUIDPipe) id: string, @Body() dto: UpdateTransportPricingDto) {
    const result = await this.service.update(id, dto);
    return successResponse(result, result.message);
  }

  @Delete(':id')
  @Permissions({ module: ModuleName.TRANSPORT_PRICING, accessLevel: AccessLevel.DELETE })
  async remove(@Param('id', ParseUUIDPipe) id: string) {
    const result = await this.service.remove(id);
    return successResponse(result, result.message);
  }
}
