import { Controller, Get, Param, Query, Res } 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";

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

    @Get('csv/:year/:period_no')
    @ModuleAccessAllowed(ModulesEnum.employee_management)
    async exportCsv(
        @Query('approved') approved: string,
        @Query('shifts') shifts: string,
        @Query('expenses') expenses: string,
        @Query('holiday') holiday: string,
        @Query('vacation') vacation: string,
        @Query('targo') targo: string,
        @Query('solucom') solucom: string,
        @Param('year') year: number,
        @Param('period_no') period_no: number,
        @Res() response: Response,
    ): Promise<void> {
        const rows = await this.csvService.collectTransaction(
            year,
            period_no,
            {
                approved: approved === 'true',
                types: {
                    shifts: shifts === 'true',
                    expenses: expenses === 'true',
                    holiday: holiday === 'true',
                    vacation: vacation === 'true',
                },
                companies: {
                    targo: targo === 'true',
                    solucom: solucom === 'true',
                },
            }
        );
        const csv_buffer = await this.generator.generateCsv(rows);

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

}