<?php

declare(strict_types=1);

namespace App\Support;

use App\Models\DberpCustomer;
use App\Models\DberpProduct;
use App\Models\DberpProductCategory;
use App\Models\DberpSupplier;
use App\Models\DberpWarehouse;
use Illuminate\Support\Facades\Cache;

/**
 * Filament 筛选/表单主数据下拉选项；短 TTL 缓存减轻重复查询，选项展示编码｜名称等业务化标签。
 */
final class DberpFilamentMasterDataSelectOptions
{
    /**
     * @return array<int|string, string>
     */
    public static function customers(bool $enabledOnly = false): array
    {
        $cacheKey = 'dberp.filament.select.customers.'.($enabledOnly ? 'enabled' : 'all');

        return Cache::remember(
            $cacheKey,
            now()->addSeconds(self::cacheSeconds()),
            function () use ($enabledOnly): array {
                $query = DberpCustomer::query()->orderBy('sort_order')->orderBy('id');

                if ($enabledOnly) {
                    $query->where('is_enabled', true);
                }

                return $query->pluck('name', 'id')->all();
            },
        );
    }

    /**
     * @return array<int|string, string>
     */
    public static function suppliers(bool $enabledOnly = false): array
    {
        $cacheKey = 'dberp.filament.select.suppliers.'.($enabledOnly ? 'enabled' : 'all');

        return Cache::remember(
            $cacheKey,
            now()->addSeconds(self::cacheSeconds()),
            function () use ($enabledOnly): array {
                $query = DberpSupplier::query()->orderBy('sort_order')->orderBy('id');

                if ($enabledOnly) {
                    $query->where('is_enabled', true);
                }

                return $query->pluck('name', 'id')->all();
            },
        );
    }

    /**
     * @return array<int|string, string>
     */
    public static function warehouses(bool $enabledOnly = true): array
    {
        $cacheKey = 'dberp.filament.select.warehouses.'.($enabledOnly ? 'enabled' : 'all');

        return Cache::remember(
            $cacheKey,
            now()->addSeconds(self::cacheSeconds()),
            function () use ($enabledOnly): array {
                $query = DberpWarehouse::query()->orderBy('sort_order')->orderBy('id');

                if ($enabledOnly) {
                    $query->where('is_enabled', true);
                }

                return $query->pluck('name', 'id')->all();
            },
        );
    }

    /**
     * @return array<int|string, string>
     */
    public static function productCategories(): array
    {
        return Cache::remember(
            'dberp.filament.select.product_categories',
            now()->addSeconds(self::cacheSeconds()),
            fn (): array => DberpProductCategory::query()
                ->orderBy('sort_order')
                ->orderBy('id')
                ->pluck('name', 'id')
                ->all(),
        );
    }

    /**
     * @param  string|null  $scope  {@see DberpProductSkuSelectOptions::PRODUCT_SCOPE_*}，为空表示全部商品（可配合 enabledOnly）
     * @return array<int|string, string>
     */
    public static function products(bool $enabledOnly = false, ?string $scope = null): array
    {
        $cacheKey = 'dberp.filament.select.products.'
            .($enabledOnly ? 'enabled' : 'all')
            .'.'
            .($scope ?? 'all')
            .'.v2';

        return Cache::remember(
            $cacheKey,
            now()->addSeconds(self::cacheSeconds()),
            function () use ($enabledOnly, $scope): array {
                if ($scope !== null) {
                    return DberpProductSkuSelectOptions::productOptionsForScope($scope);
                }

                $query = DberpProduct::query()->orderBy('sort_order')->orderBy('id');

                if ($enabledOnly) {
                    $query->where('is_enabled', true);
                }

                return DberpProductSkuSelectOptions::mapProductIterableToOptions(
                    $query->with('unit')->get(),
                );
            },
        );
    }

    private static function cacheSeconds(): int
    {
        return max(0, (int) config('dberp.filament.master_data_cache_seconds', 300));
    }
}
