import {
    Controller,
    Get,
    Post,
    Query,
    Body,
    HttpCode,
    HttpStatus,
} from '@nestjs/common';
import { TrendsService } from './trends.service';
import {CollectNowDto, GetTrendsDto} from "./dto/get-trends.dto";
import {ApiOperation, ApiResponse} from "@nestjs/swagger";
import {GoogleTrendsService} from "../collector/google-trends.service";
import googleTrends from "@shaivpidadi/trends-js";

@Controller('trends')
export class TrendsController {
    constructor(
        private readonly trendsService: TrendsService,
        private readonly googleTrendsService: GoogleTrendsService,
    ) {}

    @Get()
    async getTrends(@Query() dto: GetTrendsDto) {
        return this.trendsService.getTrends(dto);
    }

    @Get('stats')
    async getStats() {
        return this.trendsService.getStats();
    }

    @Post('collect')
    @HttpCode(HttpStatus.OK)
    @ApiOperation({ summary: 'Trigger thu thập trends ngay lập tức' })
    @ApiResponse({ status: 200, description: 'Kết quả thu thập' })
    async collectNow(@Body() dto: CollectNowDto) {
        const result = await this.trendsService.collectAndStore(dto.source);
        return {
            message: 'Collection completed',
            stats: result.stats,
        };
    }

    @Post('cleanup')
    @HttpCode(HttpStatus.OK)
    @ApiOperation({ summary: 'Xóa trends cũ' })
    async cleanup(@Query('days') days: number = 7) {
        const deleted = await this.trendsService.cleanupOldTrends(days);
        return { message: `Deleted ${deleted} old trends` };
    }

    @Get('test')
    async testTrends() {
        // return googleTrends.dailyTrends({
        //     trendDate: new Date(),
        //     geo: 'JP',
        // });
        // const result = await googleTrends.realTimeTrends({
        //     geo: 'JP', // Default: 'US'
        //     trendingHours: 4, // Default: 4
        // });
        // return result;
        return this.googleTrendsService.collect('JP')
    }
}
