import { Injectable } from "@nestjs/common";
import { CsvRow } from "src/time-and-attendance/exports/export-csv-options.dto";

@Injectable()
export class CsvGeneratorService {
    //csv builder and "mise en page"
    generateCsv(rows: CsvRow[]): Buffer {
        const header = [
            'company_code',
            'external_payroll_id',
            'full_name',
            'bank_code',
            'quantity_hours',
            'amount',
            'week_number',
            'pay_date',
            'holiday_date',
        ].join(';') + '\n';

        const body = rows.map(row => {
            const full_name = `${String(row.full_name).replace(/"/g, '""')}`;
            const quantity_hours = (typeof row.quantity_hours === 'number') ? row.quantity_hours.toFixed(2) : '';
            const amount = (typeof row.amount === 'number') ? row.amount.toFixed(2) : '';
            return [
                row.company_code,
                row.external_payroll_id,
                full_name,
                row.bank_code,
                quantity_hours,
                amount,
                row.week_number,
                row.pay_date,
                row.holiday_date ?? '',
            ].join(';');
        }).join('\n');
        return Buffer.from('\uFEFF' + header + body, 'utf8');
    }
}