import {
  Controller,
  Get,
  Query,
  Res,
  StreamableFile,
  UseGuards,
} from '@nestjs/common';
import type { Response } from 'express';
import { LogActivity } from '@/common/decorators/activity-log.decorator';
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
import { JwtAuthGuard } from '@/modules/auth/jwt-auth.guard';
import { RolesGuard } from '@/casl/roles.guard';
import { Roles } from '@/casl/roles.decorator';
import { ActivityLogsService } from './activity-logs.service';
import { ActivityLogQueryDto } from './dto/activity-log-query.dto';

@ApiTags('activity-logs')
@ApiBearerAuth('access-token')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('admin', 'Administrator')
@Controller('activity-logs')
export class ActivityLogsController {
  constructor(private readonly logs: ActivityLogsService) {}

  @Get('filter-options')
  filterOptions() {
    return this.logs.filterOptions();
  }

  // The filtered log as Excel. Exporting the log is itself logged.
  @Get('export')
  @LogActivity({
    summaryOnly: true,
    module: 'activity-logs',
    action: 'EXPORT',
    reference: 'activity-logs/export',
  })
  async export(
    @Query() query: ActivityLogQueryDto,
    @Res({ passthrough: true }) response: Response,
  ): Promise<StreamableFile> {
    const { buffer, filename } = await this.logs.exportWorkbook(query);
    response.set({
      'Content-Type':
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      'Content-Disposition': `attachment; filename="${filename}"`,
    });
    return new StreamableFile(buffer);
  }

  @Get()
  findAll(@Query() query: ActivityLogQueryDto) {
    return this.logs.findAll(query);
  }
}
