<?php

namespace Database\Seeders;

use App\Models\Package;
use App\Services\Paddle\PaddleGiftVoucherCatalogService;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Schema;

class GiftVoucherTierSeeder extends Seeder
{
    public function __construct(private readonly PaddleGiftVoucherCatalogService $catalog) {}

    public function run(): void
    {
        if (! config('paddle.api_key')) {
            $this->command?->warn('Skipping gift voucher Paddle sync: paddle.api_key not configured.');

            return;
        }

        $tiers = $this->buildTiers();

        foreach ($tiers as $tier) {
            $result = $this->catalog->ensureTier($tier);

            $this->command?->info(sprintf(
                '%s → product %s, price %s',
                $tier['key'],
                $result['product_id'],
                $result['price_id']
            ));
        }
    }

    /**
     * @return array<int, array{key:string,label:string,amount:float,currency?:string,paddle_product_id?:string|null,paddle_price_id?:string|null}>
     */
    protected function buildTiers(): array
    {
        $columns = ['slug', 'name', 'price'];
        if (Schema::hasColumn('packages', 'currency')) {
            $columns[] = 'currency';
        }

        $packages = Package::query()
            ->where('type', 'endcustomer')
            ->whereNotNull('price')
            ->get($columns)
            ->unique(fn (Package $package) => $package->price.'|'.($package->currency ?? 'EUR'));

        return $packages->map(function (Package $package): array {
            $amount = (float) $package->price;
            $currency = $package->currency ?? 'EUR';

            return [
                'key' => 'gift-'.$package->slug,
                'label' => 'Gutschein '.$package->name,
                'amount' => $amount,
                'currency' => $currency,
                'paddle_price_id' => $this->lookupPaddlePriceId($package->slug),
            ];
        })->values()->all();
    }

    protected function lookupPaddlePriceId(string $slug): ?string
    {
        return match ($slug) {
            'starter' => 'pri_01kbwccfe1mpwh7hh60eygemx6',
            'standard' => 'pri_01kbwccfvzrf4z2f1r62vns7gh',
            'pro' => 'pri_01kbwccg8vjc5cwz0kftfvf9wm',
            'premium' => 'pri_01kbwccgnjzwrjy5xg1yp981p6',
            default => null,
        };
    }
}
