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

class LeaveReportExportHandler implements ExportHandlerInterface
{
    public function __construct(
        private readonly LeaveRequestRepository $leaves,
        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([
            'id',
            'employee',
            'leave_type',
            'start_date',
            'end_date',
            'total_days',
            'status',
            'created_at',
        ]);
        $rows = 0;
        foreach ($this->leaves->cursorForTenant($tenantId) as $req) {
            $csv->writeRow([
                $req->id,
                $req->employee?->full_name,
                $req->leaveType?->name,
                $req->start_date?->format('Y-m-d'),
                $req->end_date?->format('Y-m-d'),
                $req->total_days,
                $req->status,
                $req->created_at?->format('Y-m-d H:i:s'),
            ]);
            $rows++;
        }
        $csv->close();
        $name = 'leave_'.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,
        ]);
    }
}
