import { Controller, Get, Post, Param, Query, Body, UseGuards, Req, NotFoundException } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiBearerAuth } from '@nestjs/swagger';
import { JwtAuthGuard, RolesGuard, Roles, UserRole } from '@genex/common';
import { AdminReportsService } from '../../../application/services/admin-reports.service';
import { ReportStatus } from '../../../domain/entities/report.entity';
import { GenerateReportDto, ListReportsQueryDto } from '../dto/report.dto';

@ApiTags('Admin - Reports')
@Controller('admin/reports')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles(UserRole.ADMIN)
@ApiBearerAuth()
export class AdminReportsController {
  constructor(private readonly adminReportsService: AdminReportsService) {}

  @Get()
  @ApiOperation({ summary: 'List all generated reports' })
  async listReports(@Query() query: ListReportsQueryDto) {
    return {
      code: 0,
      data: await this.adminReportsService.listReports(
        +(query.page || '1'),
        +(query.limit || '20'),
        query.type,
      ),
    };
  }

  @Post('generate')
  @ApiOperation({ summary: 'Trigger report generation (daily/monthly/quarterly/annual)' })
  async generateReport(@Body() body: GenerateReportDto, @Req() req: any) {
    const userId = req.user?.sub || req.user?.id || 'system';
    return { code: 0, data: await this.adminReportsService.generateReport(body, userId) };
  }

  @Get(':id/download')
  @ApiOperation({ summary: 'Download a generated report' })
  async downloadReport(@Param('id') id: string) {
    const report = await this.adminReportsService.getReportForDownload(id);
    if (report.status !== ReportStatus.GENERATED || !report.fileUrl) {
      throw new NotFoundException('Report is not yet generated or generation failed');
    }
    return {
      code: 0,
      data: {
        id: report.id,
        title: report.title,
        type: report.type,
        period: report.period,
        fileUrl: report.fileUrl,
        generatedAt: report.generatedAt,
      },
    };
  }
}
