<?php

namespace Database\Seeders;

use App\Models\AdCode;
use App\Models\Category;
use App\Models\Comment;
use App\Models\Like;
use App\Models\Setting;
use App\Models\Subscription;
use App\Models\User;
use App\Models\Video;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

class DatabaseSeeder extends Seeder
{
    public function run(): void
    {
        /* ---------------- Users ---------------- */
        $admin = User::updateOrCreate(
            ['email' => 'admin@streamhub.test'],
            [
                'name' => 'Admin',
                'password' => Hash::make('password'),
                'is_admin' => true,
                'avatar' => 'https://i.pravatar.cc/150?img=12',
            ]
        );

        $user = User::updateOrCreate(
            ['email' => 'user@streamhub.test'],
            [
                'name' => 'Demo Viewer',
                'password' => Hash::make('password'),
                'is_admin' => false,
                'avatar' => 'https://i.pravatar.cc/150?img=32',
            ]
        );

        /* ---------------- Settings ---------------- */
        $settings = [
            'site_name' => 'StreamHub',
            'logo_url' => '',
            'theme_primary' => '#6366f1',
            'theme_dark' => '1',
            'channel_name' => 'StreamHub Official',
            'channel_avatar' => 'https://i.pravatar.cc/150?img=12',

            'marquee_enabled' => '1',
            'marquee_text' => '🔥 Welcome to StreamHub — new exclusive videos added daily! Subscribe for more.',
            'marquee_link' => '',
            'marquee_speed' => '30',
            'marquee_bg' => '#4f46e5',
            'marquee_color' => '#ffffff',

            'ad_grid_frequency' => '6',
            'ad_grid_random' => '1',
            'ad_break_interval' => '180',
            'ad_break_enabled' => '1',
        ];
        foreach ($settings as $k => $v) {
            Setting::set($k, $v);
        }

        /* ---------------- Categories ---------------- */
        $categoryNames = ['Trending', 'Movies', 'Music', 'Gaming', 'Sports', 'Education', 'Comedy', 'Tech'];
        $categories = [];
        foreach ($categoryNames as $i => $name) {
            $categories[$name] = Category::updateOrCreate(
                ['slug' => Str::slug($name)],
                ['name' => $name, 'position' => $i]
            );
        }

        /* ---------------- Videos ---------------- */
        $bucket = 'https://commondatastorage.googleapis.com/gtv-videos-bucket/sample';
        $img = $bucket . '/images';

        $library = [
            ['Big Buck Bunny', 'BigBuckBunny', 'Movies', 596, ['animation', 'short', 'blender']],
            ['Elephant Dream', 'ElephantsDream', 'Movies', 653, ['animation', 'short', 'scifi']],
            ['For Bigger Blazes', 'ForBiggerBlazes', 'Tech', 15, ['chromecast', 'promo']],
            ['For Bigger Escapes', 'ForBiggerEscapes', 'Trending', 15, ['chromecast', 'promo']],
            ['For Bigger Fun', 'ForBiggerFun', 'Comedy', 60, ['chromecast', 'fun']],
            ['For Bigger Joyrides', 'ForBiggerJoyrides', 'Sports', 15, ['cars', 'promo']],
            ['For Bigger Meltdowns', 'ForBiggerMeltdowns', 'Music', 15, ['chromecast', 'promo']],
            ['Sintel', 'Sintel', 'Movies', 888, ['animation', 'fantasy', 'blender']],
            ['Subaru Outback On Street And Dirt', 'SubaruOutbackOnStreetAndDirt', 'Sports', 594, ['cars', 'offroad']],
            ['Tears of Steel', 'TearsOfSteel', 'Movies', 734, ['scifi', 'blender', 'vfx']],
            ['Volkswagen GTI Review', 'VolkswagenGTIReview', 'Tech', 500, ['cars', 'review']],
            ['We Are Going On Bullrun', 'WeAreGoingOnBullrun', 'Gaming', 47, ['cars', 'race']],
        ];

        $videos = [];
        foreach ($library as $i => [$title, $file, $cat, $duration, $tags]) {
            $videos[] = Video::updateOrCreate(
                ['slug' => Str::slug($title)],
                [
                    'title' => $title,
                    'description' => "Enjoy \"$title\" in high quality on StreamHub. "
                        . 'This is demo content seeded for testing the platform.',
                    'thumbnail' => "$img/$file.jpg",
                    'source_type' => 'file',
                    'source_url' => "$bucket/$file.mp4",
                    'category_id' => $categories[$cat]->id,
                    'tags' => $tags,
                    'duration' => $duration,
                    'status' => 'published',
                    'is_exclusive' => $i === 7,
                    'is_live' => $i === 3,
                    'fake_views' => rand(1200, 250000),
                    'fake_likes' => rand(50, 9000),
                    'fake_comments' => rand(5, 400),
                    'fake_shares' => rand(10, 1500),
                    'views' => rand(0, 500),
                ]
            );
        }

        /* ---------------- A LOCKED demo video ---------------- */
        $locked = Video::updateOrCreate(
            ['slug' => 'exclusive-locked-premiere'],
            [
                'title' => 'Exclusive Locked Premiere 🔒',
                'description' => 'This premium video is locked. Visit the sponsor a few times to unlock it — '
                    . 'the unlock is fully verified on the server.',
                'thumbnail' => "$img/TearsOfSteel.jpg",
                'source_type' => 'file',
                'source_url' => "$bucket/TearsOfSteel.mp4",
                'category_id' => $categories['Trending']->id,
                'tags' => ['exclusive', 'premium', 'locked'],
                'duration' => 734,
                'status' => 'published',
                'is_exclusive' => true,
                'is_locked' => true,
                'required_ad_visits' => 3,
                'ad_links' => [
                    'https://example.com/sponsor?ad=1',
                    'https://example.com/sponsor?ad=2',
                    'https://example.com/sponsor?ad=3',
                ],
                'return_seconds' => 20,
                'unlock_expiry_hours' => 24,
                'fake_views' => 87000,
                'fake_likes' => 4200,
                'fake_comments' => 120,
                'fake_shares' => 640,
            ]
        );

        /* Featured exclusive/live item shown on the home page. */
        Setting::set('exclusive_video_id', $locked->id);

        /* ---------------- Engagement ---------------- */
        Subscription::firstOrCreate(['user_id' => $user->id]);

        foreach (array_slice($videos, 0, 5) as $v) {
            Like::firstOrCreate(['video_id' => $v->id, 'user_id' => $user->id]);
            Comment::firstOrCreate(
                ['video_id' => $v->id, 'user_id' => $user->id],
                ['body' => 'Great video, thanks for sharing! 🔥']
            );
            Comment::firstOrCreate(
                ['video_id' => $v->id, 'user_id' => $admin->id],
                ['body' => 'Glad you enjoyed it — more coming soon!']
            );
        }

        /* ---------------- Ad codes ---------------- */
        $placeholder = fn (string $label, string $color) =>
            '<div style="display:flex;align-items:center;justify-content:center;min-height:120px;'
            . 'background:' . $color . ';color:#fff;font:600 15px system-ui;border-radius:12px;text-align:center;padding:16px;">'
            . '📢 ' . $label . '<br><span style="font-weight:400;opacity:.8">(replace with your ad code)</span></div>';

        $ads = [
            ['Grid Banner', 'grid', $placeholder('Sponsored — In-Grid Ad', '#0f766e')],
            ['Below Video', 'below_video', $placeholder('Sponsored — Below Video', '#7c3aed')],
            ['In-Player Break', 'in_player', $placeholder('Ad Break — Watch to continue', '#b91c1c')],
            ['Lock Screen', 'lock_screen', $placeholder('Sponsor Ad', '#c2410c')],
        ];
        foreach ($ads as $pos => [$name, $placement, $code]) {
            AdCode::updateOrCreate(
                ['placement' => $placement, 'name' => $name],
                ['code' => $code, 'enabled' => true, 'position' => $pos]
            );
        }

        $this->command?->info('Seeded: 2 users, ' . count($categoryNames) . ' categories, '
            . (count($library) + 1) . ' videos (1 locked), 4 ad codes.');
    }
}
