<?php

namespace App\Modules\Exports\ExportHandlers;

use App\Modules\Exports\ExportHandlers\Contracts\ExportHandlerInterface;
use App\Modules\Exports\Models\Export;
use App\Modules\Exports\Repositories\ExportRepository;
use App\Modules\Exports\Support\CsvStreamWriter;
use App\Modules\HR\Recruitment\DTOs\RecruitmentReportFilters;
use App\Modules\HR\Recruitment\Services\RecruitmentReportRegistry;
use App\Modules\HR\Recruitment\Support\RecruitmentReportType;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\Storage;
use InvalidArgumentException;

class RecruitmentReportExportHandler implements ExportHandlerInterface
{
    public function __construct(
        private readonly RecruitmentReportRegistry $registry,
        private readonly ExportRepository $exports,
    ) {}

    public function handle(Export $export): void
    {
        $filtersArr = is_array($export->filters) ? $export->filters : [];
        $type = (string) ($filtersArr['report_type'] ?? RecruitmentReportType::FUNNEL);
        if (! RecruitmentReportType::isValid($type)) {
            throw new InvalidArgumentException('Invalid recruitment report type: '.$type);
        }

        $report = $this->registry->build(
            $type,
            (int) $export->tenant_id,
            RecruitmentReportFilters::fromArray($filtersArr),
        );

        $relPath = 'exports/'.$export->tenant_id.'/'.$export->id.'.csv';
        $csv = new CsvStreamWriter(Storage::disk('local')->path($relPath));
        $csv->open();
        $csv->writeRow(array_map(
            fn ($c) => __('recruitment.reports.columns.'.$c),
            $report['columns']
        ));
        $rows = 0;
        foreach ($report['rows'] as $row) {
            $csv->writeRow($row);
            $rows++;
        }
        $csv->close();

        $this->exports->update($export, [
            'file_path' => $relPath,
            'file_name' => 'recruitment_'.$type.'_'.CarbonImmutable::now()->format('Ymd_His').'.csv',
            'mime_type' => 'text/csv; charset=UTF-8',
            'total_rows' => $rows,
        ]);
    }
}
