<?php

namespace App\Modules\HR\Recruitment\Services;

use App\Modules\HR\Recruitment\DTOs\RecruitmentReportFilters;
use Symfony\Component\HttpFoundation\StreamedResponse;

class RecruitmentReportExcelExportService
{
    public function __construct(
        private readonly RecruitmentReportRegistry $registry,
    ) {}

    public function download(string $type, int $tenantId, RecruitmentReportFilters $filters): StreamedResponse
    {
        $report = $this->registry->build($type, $tenantId, $filters);
        $filename = 'recruitment_'.$type.'_'.now()->format('Ymd_His').'.xls';

        return response()->streamDownload(function () use ($report): void {
            echo "\xEF\xBB\xBF";
            $out = fopen('php://output', 'wb');
            if ($out === false) {
                return;
            }
            fputcsv($out, array_map(
                fn ($c) => __('recruitment.reports.columns.'.$c),
                $report['columns']
            ));
            foreach ($report['rows'] as $row) {
                fputcsv($out, $row);
            }
            fclose($out);
        }, $filename, [
            'Content-Type' => 'application/vnd.ms-excel; charset=UTF-8',
        ]);
    }
}
