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

class AttendanceExceptionsReportExportHandler implements ExportHandlerInterface
{
    public function __construct(
        private readonly AttendanceExceptionRepository $exceptions,
        private readonly ExportRepository $exports,
    ) {}

    public function handle(Export $export): void
    {
        $tenantId = (int) $export->tenant_id;
        $filters = is_array($export->filters) ? $export->filters : [];
        $relPath = 'exports/'.$tenantId.'/'.$export->id.'.csv';
        $csv = new CsvStreamWriter(Storage::disk('local')->path($relPath));
        $csv->open();
        $csv->writeRow([
            'id',
            'employee',
            'type',
            'severity',
            'status',
            'detected_at',
            'attendance_date',
        ]);
        $rows = 0;
        foreach ($this->exceptions->cursorForTenant($tenantId, $filters) as $ex) {
            $csv->writeRow([
                $ex->id,
                $ex->employee?->full_name,
                $ex->type,
                $ex->severity,
                $ex->status,
                $ex->detected_at?->format('Y-m-d H:i:s'),
                $ex->attendanceRecord?->attendance_date?->format('Y-m-d'),
            ]);
            $rows++;
        }
        $csv->close();
        $name = 'attendance_exceptions_'.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,
        ]);
    }
}
