import {
  Controller,
  Post,
  Body,
  Get,
  Param,
  Res,
  HttpCode,
  HttpStatus,
  NotFoundException,
} from '@nestjs/common';
import {
  ApiTags,
  ApiOperation,
  ApiResponse,
  ApiBearerAuth,
} from '@nestjs/swagger';
import { Response } from 'express';
import * as fs from 'fs';
import { ExportReportDto } from '../dto/request/export-report.dto';
import { ReportFileResponseDto } from '../dto/response/report-file.dto';
import { ExportReportHandler } from '../../application/commands/export-report/export-report.handler';
import { ExportReportCommand } from '../../application/commands/export-report/export-report.command';

@ApiTags('Export')
@Controller('export')
@ApiBearerAuth()
export class ExportController {
  constructor(private readonly exportReportHandler: ExportReportHandler) {}

  @Post()
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: '导出报表' })
  @ApiResponse({
    status: 200,
    description: '导出成功',
    type: ReportFileResponseDto,
  })
  async exportReport(
    @Body() dto: ExportReportDto,
  ): Promise<ReportFileResponseDto> {
    const command = new ExportReportCommand(BigInt(dto.snapshotId), dto.format);

    const file = await this.exportReportHandler.execute(command);

    return {
      id: file.id?.toString() || '',
      fileName: file.fileName,
      fileUrl: file.fileUrl || '',
      fileSize: file.fileSize.toString(),
      fileFormat: file.fileFormat,
      mimeType: file.mimeType,
      createdAt: file.createdAt,
    };
  }

  @Get('download/:fileId')
  @ApiOperation({ summary: '下载报表文件' })
  @ApiResponse({ status: 200, description: '文件下载' })
  @ApiResponse({ status: 404, description: '文件不存在' })
  async downloadFile(
    @Param('fileId') fileId: string,
    @Res() res: Response,
  ): Promise<void> {
    // In a real implementation, you would:
    // 1. Look up the file record from database
    // 2. Verify user has access
    // 3. Stream the file

    // For now, return a placeholder response
    throw new NotFoundException(`File not found: ${fileId}`);
  }
}
