import {
  Controller,
  Post,
  Body,
  Get,
  Query,
  UsePipes,
  ValidationPipe,
  HttpCode,
  HttpStatus,
  UseGuards,
} from '@nestjs/common';
import { AnalyticsService } from './analytics.service';
import {
  TrackShareDto,
  GetShareStatsDto,
  ShareStatsResponse,
} from './analytics.dto';
import { Public } from '../auth/public.decorator';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { RolesGuard } from '../auth/roles.guard';
import { Roles } from '../auth/roles.decorator';
import { UserRole } from '../entities';

@Controller('analytics')
export class AnalyticsController {
  constructor(private readonly analyticsService: AnalyticsService) {}

  @Public()
  @Post('share')
  @HttpCode(HttpStatus.CREATED)
  @UsePipes(new ValidationPipe({ transform: true }))
  async trackShare(@Body() trackShareDto: TrackShareDto) {
    return await this.analyticsService.trackShare(trackShareDto);
  }

  @UseGuards(JwtAuthGuard, RolesGuard)
  @Roles(UserRole.ADMIN)
  @Get('shares')
  @UsePipes(new ValidationPipe({ transform: true }))
  async getShareStats(
    @Query() getShareStatsDto: GetShareStatsDto,
  ): Promise<ShareStatsResponse[]> {
    return await this.analyticsService.getShareStats(getShareStatsDto);
  }

  @UseGuards(JwtAuthGuard, RolesGuard)
  @Roles(UserRole.ADMIN)
  @Get('shares/top')
  async getTopSharedArticles(@Query('limit') limit: string) {
    const limitNum = limit ? parseInt(limit) : 10;
    return await this.analyticsService.getTopSharedArticles(limitNum);
  }

  @UseGuards(JwtAuthGuard, RolesGuard)
  @Roles(UserRole.ADMIN)
  @Get('shares/trends')
  async getShareTrends(
    @Query('startDate') startDate: string,
    @Query('endDate') endDate: string,
    @Query('interval') interval: 'day' | 'week' | 'month',
  ) {
    return await this.analyticsService.getShareTrends(
      new Date(startDate),
      new Date(endDate),
      interval || 'day',
    );
  }

  @UseGuards(JwtAuthGuard, RolesGuard)
  @Roles(UserRole.ADMIN)
  @Get('shares/total')
  async getTotalShareStats() {
    return await this.analyticsService.getTotalShareStats();
  }
}
