<?php

namespace App\Services;

use App\Models\Setting;
use InvalidArgumentException;

class EmbedProviderService
{
    /**
     * Configurable providers for licensed/self-hosted embed endpoints.
     * Templates support: {tmdb_id}, {imdb_id}, {season}, {episode}.
     */
    public function providers(): array
    {
        $providers = [];

        foreach (['primary', 'alternative', 'free'] as $key) {
            $name = trim((string) Setting::getValue("embed_{$key}_name", ucfirst($key) . ' Server'));
            $movie = trim((string) Setting::getValue("embed_{$key}_movie_template", ''));
            $tv = trim((string) Setting::getValue("embed_{$key}_tv_template", ''));

            if ($movie === '' && $tv === '') {
                continue;
            }

            $providers[$key] = [
                'key' => $key,
                'name' => $name !== '' ? $name : ucfirst($key) . ' Server',
                'movie_template' => $movie,
                'tv_template' => $tv,
            ];
        }

        return $providers;
    }

    public function defaultKey(array $providers): ?string
    {
        return array_key_first($providers);
    }

    public function movieUrl(array $provider, object $movie): ?string
    {
        return $this->render($provider['movie_template'] ?? '', [
            'tmdb_id' => $movie->tmdb_id,
            'imdb_id' => $movie->imdb_id,
        ]);
    }

    public function episodeUrl(array $provider, object $show, object $episode): ?string
    {
        return $this->render($provider['tv_template'] ?? '', [
            'tmdb_id' => $show->tmdb_id,
            'imdb_id' => $show->imdb_id,
            'season' => $episode->season->season_number,
            'episode' => $episode->episode_number,
        ]);
    }

    private function render(string $template, array $values): ?string
    {
        if ($template === '') {
            return null;
        }

        foreach ($values as $placeholder => $value) {
            if (str_contains($template, '{' . $placeholder . '}') && ($value === null || $value === '')) {
                return null;
            }

            $template = str_replace('{' . $placeholder . '}', rawurlencode((string) $value), $template);
        }

        if (preg_match('/\{[a-z_]+\}/i', $template)) {
            return null;
        }

        $parts = parse_url($template);
        if (!is_array($parts) || !in_array(strtolower($parts['scheme'] ?? ''), ['http', 'https'], true) || empty($parts['host'])) {
            throw new InvalidArgumentException('Embed template must produce a valid HTTP or HTTPS URL.');
        }

        return $template;
    }
}
