<?php

declare(strict_types=1);

namespace App\Filament\Support;

use App\Services\DberpPermissionService;
use Closure;
use Filament\Actions\Action;
use Illuminate\Support\Facades\Auth;

final class DberpExportCsvFilamentAction
{
    public static function configure(Action $action): Action
    {
        return $action
            ->color('gray')
            ->outlined()
            ->openUrlInNewTab();
    }

    public static function forReportList(string $reportKey): Action
    {
        return self::configure(
            Action::make('export')
                ->label(__('dberp.actions.export'))
                ->visible(fn (): bool => app(DberpPermissionService::class)->allowsReportExport(Auth::user(), $reportKey))
                ->url(fn (): string => route('dberp.reports.export', ['report' => $reportKey]).'?'.http_build_query(request()->query())),
        );
    }

    /**
     * @param  Closure(): string  $urlResolver
     * @param  (Closure(): bool)|null  $visibleResolver
     */
    public static function forReportPage(string $reportKey, Closure $urlResolver, ?Closure $visibleResolver = null): Action
    {
        $action = Action::make('export')
            ->label(__('dberp.actions.export'))
            ->url($urlResolver);

        if ($visibleResolver !== null) {
            $action->visible($visibleResolver);
        } else {
            $action->visible(fn (): bool => app(DberpPermissionService::class)->allowsReportExport(Auth::user(), $reportKey));
        }

        return self::configure($action);
    }
}
