<?php
declare(strict_types=1);

function mocker_games_covers_default(): array
{
    return [
        'blackjack' => 'https://images.unsplash.com/photo-1511193311915-072cadbbbd56?auto=format&w=960&h=600&fit=crop&q=80',
        'slot' => 'https://images.unsplash.com/photo-1621407889754-8e62f294e3f2?auto=format&w=960&h=600&fit=crop&q=80',
        'roulette' => 'https://images.unsplash.com/photo-1596166300001-036a283056c6?auto=format&w=960&h=600&fit=crop&q=80',
    ];
}

function mocker_games_covers_path(): string
{
    return dirname(__DIR__) . '/data/games.json';
}

function mocker_games_covers_load(): array
{
    $defaults = mocker_games_covers_default();
    $path = mocker_games_covers_path();
    if (!is_readable($path)) {
        return $defaults;
    }
    $j = json_decode((string) file_get_contents($path), true);
    if (!is_array($j)) {
        return $defaults;
    }
    $out = [];
    foreach (array_keys($defaults) as $key) {
        $v = isset($j[$key]) ? trim((string) $j[$key]) : '';
        $out[$key] = $v !== '' ? $v : $defaults[$key];
    }

    return $out;
}

function mocker_games_covers_normalize_url(string $url, string $label): string
{
    $url = trim($url);
    if ($url === '') {
        return '';
    }
    if (!preg_match('#^https?://#i', $url)) {
        throw new InvalidArgumentException($label . ' tam adresi http:// veya https:// ile başlamalı.');
    }
    if (strlen($url) > 2048) {
        throw new InvalidArgumentException($label . ' URL çok uzun (en fazla 2048 karakter).');
    }

    return $url;
}

/** @param array<string, mixed> $input */
function mocker_games_covers_save(array $input): array
{
    $defaults = mocker_games_covers_default();
    $clean = [];
    foreach (array_keys($defaults) as $key) {
        $raw = isset($input[$key]) ? (string) $input[$key] : '';
        $label = match ($key) {
            'blackjack' => 'Blackjack görseli',
            'slot' => 'Slot görseli',
            'roulette' => 'Rulet görseli',
            default => $key,
        };
        $url = mocker_games_covers_normalize_url($raw, $label);
        $clean[$key] = $url !== '' ? $url : $defaults[$key];
    }

    $path = mocker_games_covers_path();
    $dir = dirname($path);
    if (!is_dir($dir) && !mkdir($dir, 0755, true) && !is_dir($dir)) {
        throw new RuntimeException('data klasörü oluşturulamadı');
    }
    $json = json_encode(
        $clean,
        JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
    );
    if ($json === false || file_put_contents($path, $json) === false) {
        throw new RuntimeException('games.json yazılamadı');
    }

    return $clean;
}
