import {
  Body,
  Controller,
  Get,
  Param,
  Post,
  Query,
  UseGuards,
} from '@nestjs/common';
import { SkipThrottle } from '@nestjs/throttler';
import { AllowAuth } from '../common/decorators/allow-auth.decorator';
import { RequireScopes } from '../common/decorators/require-scopes.decorator';
import { ServiceCredentialGuard } from '../common/guards/service-credential/service-credential.guard';
import { AdvisorUsageMetricsResponse } from './dto/advisor-usage-metrics.dto';
import { LookupUserDto, LookupUserResponse } from './dto/lookup-user.dto';
import {
  ResolveUuidsByEmailsDto,
  ResolveUuidsByEmailsResponse,
} from './dto/resolve-uuids-by-emails.dto';
import {
  BatchFetchUsersDto,
  BatchFetchUsersResponse,
} from './dto/batch-fetch-users.dto';
import { ListMasterUsersQueryDto } from './dto/list-users-query.dto';
import { MasterApiService } from './master-api.service';

// Server-to-server only (service-key auth via the route×method matrix). Callers reach
// this from a single egress IP, so the global per-IP throttler would cap legitimate
// traffic; the service-key validation (with negative caching) is the brute-force backstop.
@SkipThrottle()
@Controller('master-api')
@AllowAuth(['service_key'])
@RequireScopes('api:master-users:read')
@UseGuards(ServiceCredentialGuard)
export class MasterApiController {
  constructor(private readonly masterApiService: MasterApiService) {}

  @Get('users')
  searchUsers(@Query() query: ListMasterUsersQueryDto) {
    return this.masterApiService.searchUsers(query);
  }

  @Get('users/:uuid/usage-metrics')
  getAdvisorUsageMetrics(
    @Param('uuid') uuid: string,
  ): Promise<AdvisorUsageMetricsResponse> {
    return this.masterApiService.getAdvisorUsageMetrics(uuid);
  }

  @Post('users/lookup')
  lookupUser(@Body() dto: LookupUserDto): Promise<LookupUserResponse> {
    return this.masterApiService.lookupUser({
      uuid: dto.uuid,
      email: dto.email,
    });
  }

  @Post('users/resolve-uuids-by-emails')
  resolveUuidsByEmails(
    @Body() dto: ResolveUuidsByEmailsDto,
  ): Promise<ResolveUuidsByEmailsResponse> {
    return this.masterApiService.resolveUuidsByEmails(dto.emails ?? []);
  }

  @Post('users/batch-fetch')
  batchFetchUsers(
    @Body() dto: BatchFetchUsersDto,
  ): Promise<BatchFetchUsersResponse> {
    return this.masterApiService.batchFetchUsers(
      dto.uuids ?? [],
      dto.emails ?? [],
    );
  }
}
