import { Body, Controller, Param, Post, Res, StreamableFile } from "@nestjs/common";
import { CsvExportService } from "./services/csv-exports.service";
import { ModuleAccessAllowed } from "src/common/decorators/modules-guard.decorators";
import { Modules as ModulesEnum } from "prisma/postgres/generated/prisma/client/postgres/client";
// import { Response } from "express";
import { CsvGeneratorService } from "src/time-and-attendance/exports/services/csv-builder.service";
import type { CsvFilters } from "src/time-and-attendance/exports/export-csv-options.dto";

@Controller('exports')
export class CsvExportController {
    constructor(
        private readonly csvService: CsvExportService,
        private readonly generator: CsvGeneratorService,

    ) { }

    @Post('csv/:year/:period_no')
    @ModuleAccessAllowed(ModulesEnum.employee_management)
    async exportCsv(
        @Param('year') year: number,
        @Param('period_no') period_no: number,
        @Body() filters: CsvFilters,
        // @Res() response: Response,
    ) {
        const rows = await this.csvService.collectTransaction(year, period_no, filters);
        const buffer = this.generator.generateCsv(rows);

        return new StreamableFile(buffer, {
            type: 'text/csv',
            disposition: 'attachment; filename=export.csv'
        })

        // response.set({
        //     'Content-Type': 'text/csv',
        //     'Content-Disposition': 'attachment; filename="export.csv"',
        // });

        // response.send(blob);
    }
}