import { ApiTags, ApiOperation, ApiResponse, ApiBearerAuth } from '@nestjs/swagger';
import { RateLimitService } from './api-key/rate-limit/rate-limit.service';
import { Controller, UseGuards, Get, Req } from '@nestjs/common';
import { ApiKeyGuard } from 'common/guards/api-key.guard';

@ApiTags('CAN Features')
@Controller('can-features')
@UseGuards(ApiKeyGuard)
export class CanFeaturesController {
  constructor(private rateLimitService: RateLimitService) { }

  @Get('rate-limits')
  @ApiOperation({ summary: 'Get detailed rate limit information for the current API key' })
  @ApiResponse({ status: 200, description: 'Returns rate limit information' })
  @ApiBearerAuth()
  async getRateLimits(@Req() req: Request) {
    const apiKey = req['apiKey'];
    const detailedStats = await this.rateLimitService.getUsageStats(apiKey.id);

    return {
      tier: apiKey.tier,
      usageStats: detailedStats,
      resetTimes: {
        minuteReset: this.getNextResetTime(apiKey.lastMinuteReset, 'minute'),
        dailyReset: this.getNextResetTime(apiKey.lastDailyReset, 'day'),
        monthlyReset: this.getNextResetTime(apiKey.lastMonthlyReset, 'month'),
      },
    };
  }

  private getNextResetTime(lastReset: Date, type: 'minute' | 'day' | 'month'): Date {
    const nextReset = new Date(lastReset);

    switch (type) {
      case 'minute':
        nextReset.setMinutes(nextReset.getMinutes() + 1);
        break;
      case 'day':
        nextReset.setDate(nextReset.getDate() + 1);
        nextReset.setHours(0, 0, 0, 0);
        break;
      case 'month':
        nextReset.setMonth(nextReset.getMonth() + 1);
        nextReset.setDate(1);
        nextReset.setHours(0, 0, 0, 0);
        break;
    }

    return nextReset;
  }
}
