<?php

namespace App\Services\Addons;

use App\Models\PackageAddon;
use Illuminate\Support\Arr;

class EventAddonCatalog
{
    /**
     * @return array<string, mixed>
     */
    public function all(): array
    {
        $dbAddons = PackageAddon::query()
            ->where('active', true)
            ->orderBy('sort')
            ->get()
            ->mapWithKeys(function (PackageAddon $addon) {
                return [$addon->key => [
                    'label' => $addon->label,
                    'price_id' => $addon->price_id,
                    'increments' => $addon->increments,
                ]];
            })
            ->all();

        // Fallback to config and merge (DB wins)
        $configAddons = config('package-addons', []);

        return array_merge($configAddons, $dbAddons);
    }

    /**
     * @return array<string, mixed>|null
     */
    public function find(string $key): ?array
    {
        return $this->all()[$key] ?? null;
    }

    public function resolvePriceId(string $key): ?string
    {
        $addon = $this->find($key);

        return $addon['price_id'] ?? null;
    }

    /**
     * @return array<string, int>
     */
    public function resolveIncrements(string $key): array
    {
        $addon = $this->find($key) ?? [];

        $increments = Arr::get($addon, 'increments', []);

        return collect($increments)
            ->map(fn ($value) => is_numeric($value) ? (int) $value : 0)
            ->filter(fn ($value) => $value > 0)
            ->all();
    }
}
