<?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\Employees\Repositories\EmployeeRepository;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\Storage;

class EmployeesReportExportHandler implements ExportHandlerInterface
{
    public function __construct(
        private readonly EmployeeRepository $employees,
        private readonly ExportRepository $exports,
    ) {}

    public function handle(Export $export): void
    {
        $tenantId = (int) $export->tenant_id;
        $relPath = 'exports/'.$tenantId.'/'.$export->id.'.csv';
        $csv = new CsvStreamWriter(Storage::disk('local')->path($relPath));
        $csv->open();
        $csv->writeRow([
            'employee_code',
            'full_name',
            'department',
            'position',
            'email',
            'hire_date',
            'is_active',
        ]);
        $rows = 0;
        foreach ($this->employees->cursorForTenantExport($tenantId) as $e) {
            $csv->writeRow([
                $e->employee_code,
                $e->full_name,
                $e->department?->name,
                $e->position?->title,
                $e->email,
                $e->hire_date?->format('Y-m-d'),
                $e->is_active ? '1' : '0',
            ]);
            $rows++;
        }
        $csv->close();
        $name = 'employees_'.CarbonImmutable::now()->format('Ymd_His').'.csv';
        $this->exports->update($export, [
            'file_path' => $relPath,
            'file_name' => $name,
            'mime_type' => 'text/csv; charset=UTF-8',
            'total_rows' => $rows,
        ]);
    }
}
