<?php

namespace App\Modules\Exports\Services;

use App\Models\User;
use App\Modules\Exports\Events\ExportRequested;
use App\Modules\Exports\Jobs\ExportProcessorJob;
use App\Modules\Exports\Models\Export;
use App\Modules\Exports\Repositories\ExportRepository;
use App\Modules\Exports\Support\ExportStatus;
use Illuminate\Support\Facades\DB;

class ExportManagerService
{
    public function __construct(
        private readonly ExportRepository $exports,
    ) {}

    /**
     * @param  array<string, mixed>|null  $filters
     */
    public function request(User $user, string $type, ?array $filters): Export
    {
        return DB::transaction(function () use ($user, $type, $filters): Export {
            $export = $this->exports->create([
                'tenant_id' => (int) $user->tenant_id,
                'user_id' => (int) $user->id,
                'type' => $type,
                'filters' => $filters,
                'status' => ExportStatus::PENDING,
            ]);
            $exportId = (int) $export->id;
            $tenantId = (int) $export->tenant_id;
            DB::afterCommit(function () use ($exportId, $tenantId): void {
                $fresh = Export::query()->whereKey($exportId)->first();
                if ($fresh instanceof Export) {
                    event(new ExportRequested($fresh));
                    ExportProcessorJob::dispatch($tenantId, $exportId);
                }
            });

            return $export;
        });
    }
}
