<?php

namespace App\Support;

use App\Models\Setting;
use Illuminate\Http\Request;

class PageTutorialVideoRegistry
{
    public static function definitions(): array
    {
        return [
            'register' => [
                'field' => 'register_page_video_link',
                'setting_key' => 'page_tutorial_video_link_register',
                'label' => 'Registration Page Video',
                'title' => 'রেজিস্ট্রেশন ভিডিও',
                'description' => '/register পেজে এই ভিডিও button দেখাবে।',
                'route_names' => ['register'],
                'path_prefixes' => ['register'],
            ],
            'activation' => [
                'field' => 'activation_page_video_link',
                'setting_key' => 'page_tutorial_video_link_activation',
                'label' => 'Account Verification Video',
                'title' => 'একাউন্ট ভেরিফাই ভিডিও',
                'description' => '/activation flow-তে এই ভিডিও দেখাবে।',
                'route_names' => ['activation.form', 'activation.success'],
                'path_prefixes' => ['activation'],
            ],
            'facebook' => [
                'field' => 'facebook_project_video_link',
                'setting_key' => 'page_tutorial_video_link_facebook_project',
                'label' => 'Facebook Project Video',
                'title' => 'ফেসবুক প্রজেক্ট ভিডিও',
                'description' => '/fb/marketing page-এ এই ভিডিও দেখাবে।',
                'route_names' => [],
                'path_prefixes' => ['fb/marketing'],
            ],
            'micro_jobs' => [
                'field' => 'micro_jobs_video_link',
                'setting_key' => 'page_tutorial_video_link_micro_jobs',
                'label' => 'Micro Job Video',
                'title' => 'মাইক্রো জব ভিডিও',
                'description' => '/micro-jobs page-এ এই ভিডিও দেখাবে।',
                'route_names' => ['microjobs.index', 'microjobs.show'],
                'path_prefixes' => ['micro-jobs'],
            ],
            'mobile_recharge' => [
                'field' => 'mobile_recharge_video_link',
                'setting_key' => 'page_tutorial_video_link_mobile_recharge',
                'label' => 'Mobile Recharge Video',
                'title' => 'মোবাইল রিচার্জ ভিডিও',
                'description' => '/recharge page-এর top section-এ এই ভিডিও দেখাবে।',
                'route_names' => ['user.recharge.index', 'user.recharge.history'],
                'path_prefixes' => ['recharge'],
            ],
            'digital_services' => [
                'field' => 'digital_services_video_link',
                'setting_key' => 'page_tutorial_video_link_digital_services',
                'label' => 'Digital Service Video',
                'title' => 'ডিজিটাল সার্ভিস ভিডিও',
                'description' => '/dg-services page ও purchase page-এ এই ভিডিও দেখাবে।',
                'route_names' => ['user.dg_services.index', 'user.dg_services.show'],
                'path_prefixes' => ['dg-services'],
            ],
            'instagram' => [
                'field' => 'instagram_project_video_link',
                'setting_key' => 'page_tutorial_video_link_instagram_project',
                'label' => 'Instagram Project Video',
                'title' => 'ইনস্টাগ্রাম প্রজেক্ট ভিডিও',
                'description' => 'Instagram submit page-এ এই ভিডিও দেখাবে।',
                'route_names' => ['user.instagram.create', 'in.create'],
                'path_prefixes' => ['instagram/submit', 'in/create'],
            ],
        ];
    }

    public static function validationRules(): array
    {
        $rules = [];

        foreach (static::definitions() as $definition) {
            $rules[$definition['field']] = ['nullable', 'string', 'max:2048'];
        }

        return $rules;
    }

    public static function inputValues(): array
    {
        $values = [];
        $settings = static::settingsMap();

        foreach (static::definitions() as $definition) {
            $values[$definition['field']] = (string) ($settings[$definition['setting_key']] ?? '');
        }

        return $values;
    }

    public static function saveInputValues(array $values): void
    {
        foreach (static::definitions() as $definition) {
            $field = $definition['field'];
            $normalizedLink = ProjectTutorialVideo::normalizeLink((string) ($values[$field] ?? ''));
            static::saveSettingValue($definition['setting_key'], $normalizedLink);
        }
    }

    public static function resolveForRequest(Request $request): array
    {
        $routeName = $request->route()?->getName();
        $path = static::normalizePath((string) $request->path());
        $settings = static::settingsMap();

        foreach (static::definitions() as $definition) {
            if (!static::matchesDefinition($definition, $routeName, $path)) {
                continue;
            }

            $videoLink = (string) ($settings[$definition['setting_key']] ?? '');
            $player = ProjectTutorialVideo::playerForLink($videoLink);

            if ($player['link'] === '' || $player['src'] === '' || $player['type'] === '') {
                continue;
            }

            return [
                'currentProjectTutorialLink' => $player['link'],
                'currentProjectTutorialTitle' => (string) ($definition['title'] ?? ''),
                'currentProjectTutorialPlayerType' => $player['type'],
                'currentProjectTutorialPlayerSrc' => $player['src'],
            ];
        }

        return [
            'currentProjectTutorialLink' => '',
            'currentProjectTutorialTitle' => '',
            'currentProjectTutorialPlayerType' => '',
            'currentProjectTutorialPlayerSrc' => '',
        ];
    }

    private static function matchesDefinition(array $definition, ?string $routeName, string $path): bool
    {
        foreach (($definition['route_names'] ?? []) as $candidate) {
            if ($routeName === $candidate) {
                return true;
            }
        }

        foreach (($definition['path_prefixes'] ?? []) as $prefix) {
            $prefix = static::normalizePath((string) $prefix);
            if ($path === $prefix || str_starts_with($path, $prefix . '/')) {
                return true;
            }
        }

        return false;
    }

    private static function normalizePath(string $path): string
    {
        $path = trim($path, '/');
        return $path;
    }

    private static function settingsMap(): array
    {
        $keys = array_map(
            static fn (array $definition): string => (string) $definition['setting_key'],
            static::definitions()
        );

        return Setting::query()
            ->whereIn('key', $keys)
            ->orderByDesc('id')
            ->get(['key', 'value'])
            ->unique('key')
            ->pluck('value', 'key')
            ->map(static fn ($value): string => (string) $value)
            ->all();
    }

    private static function saveSettingValue(string $key, string $value): void
    {
        if ($value === '') {
            Setting::query()->where('key', $key)->delete();
            return;
        }

        $updated = Setting::query()
            ->where('key', $key)
            ->update(['value' => $value]);

        if ($updated === 0) {
            Setting::query()->create([
                'key' => $key,
                'value' => $value,
            ]);
        }
    }
}
