import { BadRequestException, Controller, Get, Query } from '@nestjs/common';
import { z } from 'zod';
import { PERIOD_FILTERS, type PeriodFilterT, type AuthUser } from '@vihar/shared';
import { StatsService } from './stats.service';
import { ZodValidationPipe } from '../../common/pipes/zod-validation.pipe';
import { CurrentUser, RequiresCaptain } from '../../common/decorators/auth.decorators';

const periodQuerySchema = z.object({
  period: z.enum(PERIOD_FILTERS).default('this_month'),
});

const leaderboardQuerySchema = z.object({
  period: z.enum(PERIOD_FILTERS).default('this_month'),
  metric: z.enum(['km', 'count', 'streak']).default('km'),
  localityId: z.coerce.number().int().positive().optional(),
});

@Controller('stats')
export class StatsController {
  constructor(private readonly stats: StatsService) {}

  @Get('city')
  @RequiresCaptain()
  async city(
    @CurrentUser() user: AuthUser,
    @Query(new ZodValidationPipe(periodQuerySchema)) q: { period: PeriodFilterT },
  ) {
    if (!user.cityId) throw new BadRequestException('No city scope');
    return this.stats.cityStats(user.cityId, q.period);
  }

  @Get('me')
  async me(
    @CurrentUser() user: AuthUser,
    @Query(new ZodValidationPipe(periodQuerySchema)) q: { period: PeriodFilterT },
  ) {
    return this.stats.myStats(user.userId, q.period);
  }

  @Get('leaderboard')
  async leaderboard(
    @CurrentUser() user: AuthUser,
    @Query(new ZodValidationPipe(leaderboardQuerySchema)) q: ReturnType<typeof leaderboardQuerySchema.parse>,
  ) {
    if (!user.cityId) throw new BadRequestException('No city scope');
    return this.stats.leaderboard(user.cityId, q.period, q.metric);
  }
}
