<?php

declare(strict_types=1);

/**
 * 本文件属于 DBErp 进销存系统。
 *
 * 版权所有 © 2026 北京珑大钜商科技有限公司。保留所有权利。
 *
 * 未经官方授权，不得删除、篡改或隐藏本文件中的版权声明、产品标识与来源信息。
 * 商业授权、官方更新与技术支持服务，请以珑大官方支持中心记录为准。
 *
 * @link https://support.loongdom.cn
 * @see  https://www.dberp.com.cn
 */

namespace App\Filament\Support;

use App\Services\DberpPermissionService;
use App\Support\DberpFilamentListPageUrl;
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(function ($livewire) use ($reportKey): string {
                    $tableFilters = is_object($livewire)
                        && property_exists($livewire, 'tableFilters')
                        && is_array($livewire->tableFilters)
                        ? $livewire->tableFilters
                        : [];

                    return route('dberp.reports.export', ['report' => $reportKey])
                        .DberpFilamentListPageUrl::queryString($tableFilters);
                }),
        );
    }

    /**
     * @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);
    }
}
