import {
  Controller,
  Get,
  Delete,
  Put,
  Post,
  Body,
  Param,
  UseGuards,
  UseInterceptors,
  UploadedFile,
  BadRequestException,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { ApiTags, ApiBearerAuth, ApiOperation, ApiConsumes } from '@nestjs/swagger';
import { MapsService } from './maps.service';
import { UpdateRotationDto } from './dto/update-rotation.dto';
import { UploadMapDto } from './dto/upload-map.dto';
import { CurrentTenant } from '../../common/decorators/current-tenant.decorator';
import { RequirePermission } from '../../common/decorators/require-permission.decorator';
import { JwtAuthGuard } from '../../common/guards/jwt-auth.guard';
import { PermissionsGuard } from '../../common/guards/permissions.guard';

@ApiTags('maps')
@ApiBearerAuth()
@Controller('maps')
@UseGuards(JwtAuthGuard, PermissionsGuard)
export class MapsController {
  constructor(private readonly mapsService: MapsService) {}

  @Post('upload')
  @RequirePermission('map.manage')
  @ApiOperation({ summary: 'Upload a map to the library' })
  @ApiConsumes('multipart/form-data')
  @UseInterceptors(FileInterceptor('file'))
  uploadMap(
    @CurrentTenant() licenseId: string,
    @Body() dto: UploadMapDto,
    @UploadedFile() file: Express.Multer.File,
  ) {
    if (!file) {
      throw new BadRequestException('No file provided');
    }
    return this.mapsService.uploadMap(licenseId, dto, file);
  }

  @Get()
  @RequirePermission('map.view')
  @ApiOperation({ summary: 'Get all maps for tenant' })
  getMaps(@CurrentTenant() licenseId: string) {
    return this.mapsService.getMaps(licenseId);
  }

  @Delete(':id')
  @RequirePermission('map.manage')
  @ApiOperation({ summary: 'Delete map from library' })
  async deleteMap(@CurrentTenant() licenseId: string, @Param('id') mapId: string) {
    await this.mapsService.deleteMap(licenseId, mapId);
    return { deleted: true };
  }

  @Get('rotation')
  @RequirePermission('map.view')
  @ApiOperation({ summary: 'Get current map rotation' })
  getRotation(@CurrentTenant() licenseId: string) {
    return this.mapsService.getRotation(licenseId);
  }

  @Put('rotation')
  @RequirePermission('map.manage')
  @ApiOperation({ summary: 'Update map rotation order' })
  updateRotation(@CurrentTenant() licenseId: string, @Body() dto: UpdateRotationDto) {
    return this.mapsService.updateRotation(licenseId, dto);
  }
}
