<?php

namespace App\Services\Paddle;

use Illuminate\Support\Arr;
use Illuminate\Support\Str;

class PaddleGiftVoucherCatalogService
{
    public function __construct(private readonly PaddleClient $client) {}

    /**
     * @param  array{key:string,label:string,amount:float,currency?:string,paddle_product_id?:string|null,paddle_price_id?:string|null}  $tier
     * @return array{product_id:string,price_id:string}
     */
    public function ensureTier(array $tier): array
    {
        $product = $tier['paddle_product_id'] ?? null;
        $price = $tier['paddle_price_id'] ?? null;

        if (! $product) {
            $product = $this->createProduct($tier)['id'];
        }

        if (! $price) {
            $price = $this->createPrice($tier, $product)['id'];
        }

        return [
            'product_id' => $product,
            'price_id' => $price,
        ];
    }

    /**
     * @param  array{key:string,label:string,amount:float,currency?:string}  $tier
     * @return array<string, mixed>
     */
    public function createProduct(array $tier): array
    {
        $payload = [
            'name' => $tier['label'],
            'description' => sprintf('Geschenkgutschein im Wert von %.2f %s für Fotospiel Pakete.', $tier['amount'], $this->currency($tier)),
            'type' => 'standard',
            'tax_category' => 'standard',
            'custom_data' => [
                'kind' => 'gift_voucher',
                'tier_key' => $tier['key'],
                'amount' => $tier['amount'],
                'currency' => $this->currency($tier),
            ],
        ];

        $response = $this->client->post('/products', $payload);

        return Arr::get($response, 'data', $response);
    }

    /**
     * @param  array{key:string,label:string,amount:float,currency?:string}  $tier
     * @return array<string, mixed>
     */
    public function createPrice(array $tier, string $productId): array
    {
        $payload = [
            'product_id' => $productId,
            'description' => sprintf('Geschenkgutschein %.2f %s', $tier['amount'], $this->currency($tier)),
            'unit_price' => [
                'amount' => (string) $this->toMinorUnits($tier['amount']),
                'currency_code' => $this->currency($tier),
            ],
            'custom_data' => [
                'kind' => 'gift_voucher',
                'tier_key' => $tier['key'],
            ],
        ];

        $response = $this->client->post('/prices', $payload);

        return Arr::get($response, 'data', $response);
    }

    protected function currency(array $tier): string
    {
        return Str::upper($tier['currency'] ?? 'EUR');
    }

    protected function toMinorUnits(float $amount): int
    {
        return (int) round($amount * 100);
    }
}
