import { BadRequestException, Controller, Get, Query, UseGuards, UseInterceptors } from '@nestjs/common';
import { ApiHeader, ApiTags } from '@nestjs/swagger';
import { PublicApiCryptoService } from '../common/crypto/public-api-crypto.service';
import { PublicApiKeyGuard } from '../common/guards/public-api-key.guard';
import { EncryptedResponseInterceptor } from '../common/interceptors/encrypted-response.interceptor';
import { MapsService } from './maps.service';

@ApiTags('Public Maps')
@ApiHeader({ name: 'x-api-key-enc', required: true })
@UseGuards(PublicApiKeyGuard)
@UseInterceptors(EncryptedResponseInterceptor)
@Controller('maps')
export class MapsController {
  constructor(
    private readonly maps: MapsService,
    private readonly crypto: PublicApiCryptoService,
  ) {}

  @Get('url')
  url(@Query('countryName') countryName: string, @Query('stateName') stateName: string, @Query('payload') payload?: string) {
    const decrypted = payload ? this.crypto.decrypt<{ countryName?: string; stateName?: string }>(payload) : undefined;
    const safeCountry = decrypted?.countryName ?? countryName;
    const safeState = decrypted?.stateName ?? stateName;
    if (!safeCountry || !safeState) throw new BadRequestException('countryName and stateName are required');
    return this.maps.url(safeCountry, safeState);
  }
}
