<?php

declare(strict_types=1);

namespace WPStack\Sandbox\Infrastructure;

use WPStack\Sandbox\Domain\Entitlement;
use WPStack\Sandbox\Domain\ProductDefinition;

final class SettingsRepository
{
    private int $networkId;

    public function __construct(?int $networkId = null)
    {
        $this->networkId = $networkId ?? get_current_network_id();
    }

    /**
     * @return list<array<string, mixed>>
     */
    public function products(): array
    {
        $products = get_network_option(
            $this->networkId,
            'wpstack_sandbox_products',
            []
        );

        return is_array($products) ? array_values($products) : [];
    }

    /**
     * @param list<array<string, mixed>> $products
     */
    public function saveProducts(array $products, Entitlement $entitlement): int
    {
        $normalized = [];
        foreach ($products as $input) {
            try {
                $product = ProductDefinition::fromArray($input);
            } catch (\InvalidArgumentException) {
                continue;
            }
            $normalized[$product['slug']] = $product;
        }

        $normalized = array_slice(
            array_values($normalized),
            0,
            $entitlement->productLimit()
        );
        update_network_option(
            $this->networkId,
            'wpstack_sandbox_products',
            $normalized
        );

        return count($normalized);
    }

    /**
     * @return array{brand_name:string,brand_url:string,lab_label:string}
     */
    public function branding(): array
    {
        $stored = get_network_option(
            $this->networkId,
            'wpstack_sandbox_branding',
            []
        );
        $stored = is_array($stored) ? $stored : [];

        return [
            'brand_name' => (string) ($stored['brand_name'] ?? 'WP Stack Online'),
            'brand_url' => (string) ($stored['brand_url'] ?? 'https://wpstack.online/'),
            'lab_label' => (string) ($stored['lab_label'] ?? 'PLUGIN LAB'),
        ];
    }

    /**
     * @param array<string, mixed> $branding
     */
    public function saveBranding(array $branding): void
    {
        update_network_option(
            $this->networkId,
            'wpstack_sandbox_branding',
            [
                'brand_name' => sanitize_text_field((string) ($branding['brand_name'] ?? '')),
                'brand_url' => esc_url_raw((string) ($branding['brand_url'] ?? '')),
                'lab_label' => sanitize_text_field((string) ($branding['lab_label'] ?? '')),
            ]
        );
    }
}
