import {
  Controller,
  Get,
  Query,
  Param,
  Req,
  Res,
  Header,
} from '@nestjs/common';
import { Response } from 'express';
import { PatternAnalysisService } from './pattern-analysis.service';
import { PredictionService } from './prediction.service';
import { ReportService } from './report.service';

@Controller('api/v1/analytics')
export class AnalyticsController {
  constructor(
    private readonly patternAnalysisService: PatternAnalysisService,
    private readonly predictionService: PredictionService,
    private readonly reportService: ReportService,
  ) {}

  @Get('insights/:childId')
  async getInsights(
    @Req() req: any,
    @Param('childId') childId: string,
    @Query('days') days?: string,
  ) {
    const daysNum = days ? parseInt(days, 10) : 7;
    const patterns = await this.patternAnalysisService.analyzePatterns(
      childId,
      daysNum,
    );

    return {
      success: true,
      data: patterns,
    };
  }

  @Get('predictions/:childId')
  async getPredictions(@Req() req: any, @Param('childId') childId: string) {
    const predictions =
      await this.predictionService.generatePredictions(childId);

    return {
      success: true,
      data: predictions,
    };
  }

  @Get('reports/:childId/weekly')
  async getWeeklyReport(
    @Req() req: any,
    @Param('childId') childId: string,
    @Query('startDate') startDate?: string,
  ) {
    const start = startDate ? new Date(startDate) : null;
    const report = await this.reportService.generateWeeklyReport(
      childId,
      start,
    );

    return {
      success: true,
      data: report,
    };
  }

  @Get('reports/:childId/monthly')
  async getMonthlyReport(
    @Req() req: any,
    @Param('childId') childId: string,
    @Query('month') month?: string,
  ) {
    const monthDate = month ? new Date(month) : null;
    const report = await this.reportService.generateMonthlyReport(
      childId,
      monthDate,
    );

    return {
      success: true,
      data: report,
    };
  }

  @Get('export/:childId')
  async exportData(
    @Req() req: any,
    @Res() res: Response,
    @Param('childId') childId: string,
    @Query('format') format?: string,
    @Query('startDate') startDate?: string,
    @Query('endDate') endDate?: string,
  ) {
    const start = startDate ? new Date(startDate) : null;
    const end = endDate ? new Date(endDate) : null;
    const exportFormat = (format || 'json') as 'json' | 'csv' | 'pdf';

    const exportData = await this.reportService.exportData(
      childId,
      start,
      end,
      exportFormat,
    );

    // For PDF and CSV, send as downloadable file
    if (exportFormat === 'pdf' || exportFormat === 'csv') {
      const fileName = `activity-report-${childId}-${new Date().toISOString().split('T')[0]}.${exportFormat}`;

      res.setHeader('Content-Type', exportData.contentType);
      res.setHeader(
        'Content-Disposition',
        `attachment; filename="${fileName}"`,
      );

      if (exportFormat === 'pdf') {
        res.send(exportData.data);
      } else {
        res.send(exportData.data);
      }
    } else {
      // JSON format - return as regular response
      res.json({
        success: true,
        data: exportData,
      });
    }
  }
}
