import { Controller, Get, Query, Res, UseGuards } from '@nestjs/common';
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
import type { Response } from 'express';
import { Roles } from '../common/decorators/roles.decorator';
import { RolesGuard } from '../common/guards/roles.guard';
import { MANAGEMENT_ROLES } from '../common/constants/roles';
import { ExportsService } from './exports.service';

@ApiTags('exports')
@ApiBearerAuth('access-token')
@Controller('exports')
@UseGuards(RolesGuard)
@Roles(...MANAGEMENT_ROLES)
export class ExportsController {
  constructor(private readonly exports: ExportsService) {}

  @Get('trips.json')
  json(
    @Query('from') from?: string,
    @Query('to') to?: string,
    @Query('userId') userId?: string,
  ) {
    return this.exports.exportTripsJson({ from, to, userId });
  }

  @Get('trips.xlsx')
  async excel(
    @Res() res: Response,
    @Query('from') from?: string,
    @Query('to') to?: string,
    @Query('userId') userId?: string,
  ) {
    const buffer = await this.exports.exportTripsExcel({ from, to, userId });
    res.setHeader(
      'Content-Type',
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    );
    res.setHeader('Content-Disposition', 'attachment; filename=trips.xlsx');
    res.send(Buffer.from(buffer));
  }

  @Get('trips.pdf')
  pdf(
    @Res() res: Response,
    @Query('from') from?: string,
    @Query('to') to?: string,
    @Query('userId') userId?: string,
  ) {
    return this.exports.streamTripsPdf(res, { from, to, userId });
  }
}
