// map.controller.ts
import {
  Body,
  Controller,
  Delete,
  Get,
  Param,
  Patch,
  Post,
  Req,
  UploadedFile,
  UseGuards,
  UseInterceptors,
} from '@nestjs/common';
import { MapService } from './map.service';
import { CreateMapDto } from './dto/create-map.dto';
import { FileInterceptor } from '@nestjs/platform-express';
import { storageMap } from '@/common/multerConfig';
import {
  MapMember,
  MapAdmin,
  TripMember,
  TripAdmin,
} from '@/auth/decorator/permission.decorator';
import { JwtAuthGuard } from '@/auth/guards/jwt-auth/jwt-auth.guard';

@UseGuards(JwtAuthGuard)
@Controller('maps')
export class MapController {
  constructor(private readonly mapService: MapService) {}

  // =============================
  // CREATE
  // =============================
  @Post(':tripId')
  @TripAdmin()
  @UseInterceptors(
    FileInterceptor('file', {
      storage: storageMap,
      limits: {
        fileSize: 2 * 1024 * 1024, // 2MB
      },
      fileFilter: (req, file, cb) => {
        if (!file.mimetype.match(/\/(json)$/)) {
          return cb(new Error('Only json allowed'), false);
        }
        cb(null, true);
      },
    }),
  )
  create(
    @Param('tripId') tripId: string,
    @Body() dto: CreateMapDto,
    @UploadedFile() file: Express.Multer.File,
  ) {
    dto.tripId = tripId;
    return this.mapService.create(dto, file);
  }

  // =============================
  // FIND ALL BY TRIP
  // =============================
  @Get('trip/:tripId')
  @TripMember()
  findByTrip(@Param('tripId') tripId: string, @Req() req) {
    return this.mapService.findByTrip(tripId, req.isLeader);
  }

  // =============================
  // FIND ONE
  // =============================
  @Get(':id')
  @MapMember()
  findOne(@Param('id') id: string) {
    return this.mapService.findOne(id);
  }

  // =============================
  // DELETE
  // =============================
  @Delete(':id')
  @MapAdmin()
  delete(@Param('id') id: string) {
    return this.mapService.delete(id);
  }

  // =====================================
  // CHANGE ACTIVE MAP
  // =====================================
  @Patch(':tripId/change-active/:id')
  @TripAdmin()
  changeActiveMap(
    @Param('tripId') tripId: string,
    @Param('id') id: string,
  ) {
    return this.mapService.changeActiveMap(tripId, id);
  }
}
