import { Controller, Get, Query, UseGuards, Res } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiQuery, ApiSecurity } from '@nestjs/swagger';
import { Response } from 'express';
import { ApiKeyGuard } from '../../common/guards/api-key.guard';
import { RequireApiTier } from '../../common/decorators/api-tier.decorator';
import { ExportService } from './export.service';

@ApiTags('export')
@ApiSecurity('api-key')
@Controller('v1/export')
@UseGuards(ApiKeyGuard)
export class ExportController {
  constructor(private readonly exportService: ExportService) {}

  @Get('transactions')
  @RequireApiTier('institutional')
  @ApiOperation({ summary: '批量交易导出（CSV/JSON，机构API）' })
  @ApiQuery({ name: 'from', description: '起始区块' })
  @ApiQuery({ name: 'to', description: '结束区块' })
  @ApiQuery({ name: 'format', description: '导出格式', enum: ['json', 'csv'], required: false })
  async exportTransactions(
    @Query('from') from: string,
    @Query('to') to: string,
    @Query('format') format: string = 'json',
    @Res() res: Response,
  ) {
    const data = await this.exportService.exportTransactions(parseInt(from), parseInt(to));

    if (format === 'csv') {
      res.setHeader('Content-Type', 'text/csv');
      res.setHeader('Content-Disposition', `attachment; filename=transactions_${from}_${to}.csv`);
      res.send(this.exportService.toCsv(data));
    } else {
      res.json(data);
    }
  }
}
