<?php

namespace Database\Seeders;

use App\Models\User;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;

use App\Models\Role;
use App\Models\VipLevel;
use App\Models\Raffle;
use App\Models\Banner;
use Illuminate\Support\Facades\Hash;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     */
    public function run(): void
    {
        // Limpiar datos previos antes de sembrar para evitar duplicados en pruebas
        \Illuminate\Support\Facades\Schema::disableForeignKeyConstraints();
        Raffle::truncate();
        Banner::truncate();
        \App\Models\Story::truncate();
        \App\Models\ChestPrize::truncate();
        \App\Models\UserKey::truncate();
        \App\Models\ActionTicket::truncate();
        \App\Models\ChestOpening::truncate();
        \App\Models\AppSetting::truncate();
        \Illuminate\Support\Facades\Schema::enableForeignKeyConstraints();

        // 1. Sembrar Roles por Defecto
        $adminRole = Role::firstOrCreate(['name' => 'admin'], [
            'display_name' => 'Administrador',
            'description' => 'Administrador general del sistema con acceso total.',
        ]);

        $resellerRole = Role::firstOrCreate(['name' => 'reseller'], [
            'display_name' => 'Revendedor',
            'description' => 'Revendedor autorizado de boletos con código de referido.',
        ]);

        $customerRole = Role::firstOrCreate(['name' => 'customer'], [
            'display_name' => 'Cliente',
            'description' => 'Participante del sorteo con acceso a la app móvil.',
        ]);

        // 2. Sembrar Niveles VIP por Defecto
        VipLevel::firstOrCreate(['name' => 'bronce'], [
            'display_name' => 'Bronce',
            'min_tickets' => 1,
            'description' => 'Acceso a promociones y ofertas relámpago exclusivas.',
            'bonus_multiplier' => 1.00,
        ]);

        VipLevel::firstOrCreate(['name' => 'plata'], [
            'display_name' => 'Plata',
            'min_tickets' => 51,
            'description' => 'Bonificaciones adicionales en puntos y acceso anticipado.',
            'bonus_multiplier' => 1.10,
        ]);

        VipLevel::firstOrCreate(['name' => 'oro'], [
            'display_name' => 'Oro',
            'min_tickets' => 201,
            'description' => 'Sorteos exclusivos, bonificaciones especiales y boletos gratis.',
            'bonus_multiplier' => 1.25,
        ]);

        // 3. Crear Administrador Inicial Vinculado a su Rol
        if (!User::where('email', 'admin@sorteocr.com')->exists()) {
            User::create([
                'name' => 'Admin Wincar',
                'email' => 'admin@sorteocr.com',
                'password' => Hash::make('password123'),
                'role_id' => $adminRole->id,
                'status' => 'active',
            ]);
        }

        // 4. Crear Sorteos de Prueba Activos con precios de boleto específicos
        $raffle1 = Raffle::create([
            'title' => 'Porsche GT Coupé 2025',
            'description' => 'Deportivo edición limitada con gran rendimiento y diseño inigualable.',
            'commercial_value' => 25000000.00,
            'fiscal_value' => 20000000.00,
            'ticket_price' => 2500.00,
            'draw_date' => '2026-12-15 20:00:00',
            'total_tickets' => 100,
            'status' => 'active',
            'type' => 'main',
            'images_json' => ['https://images.unsplash.com/photo-1503376780353-7e6692767b70?q=80&w=600'],
        ]);

        $raffle2 = Raffle::create([
            'title' => 'SUV Black Edition',
            'description' => 'Máxima potencia y espacio familiar para viajar con estilo.',
            'commercial_value' => 32000000.00,
            'fiscal_value' => 28000000.00,
            'ticket_price' => 2000.00,
            'draw_date' => '2026-11-28 20:00:00',
            'total_tickets' => 100,
            'status' => 'active',
            'type' => 'secondary',
            'images_json' => ['https://images.unsplash.com/photo-1533473359331-0135ef1b58bf?q=80&w=600'],
        ]);

        $raffle3 = Raffle::create([
            'title' => 'Superbike Ninja 2026',
            'description' => 'Siente la velocidad con la moto deportiva más icónica del mercado.',
            'commercial_value' => 8500000.00,
            'fiscal_value' => 7500000.00,
            'ticket_price' => 1500.00,
            'draw_date' => '2026-12-05 20:00:00',
            'total_tickets' => 100,
            'status' => 'active',
            'type' => 'secondary',
            'images_json' => ['https://images.unsplash.com/photo-1568772585407-9361f9bf3a87?q=80&w=600'],
        ]);

        // 4.5 Sembrar Premios de los Cofres para cada Sorteo
        $prizes = [
            [
                'name' => 'Acción para Premio Mayor',
                'type' => 'action',
                'value' => 1.00,
                'probability' => 40.00,
                'total_quantity' => 100,
                'remaining_quantity' => 100,
            ],
            [
                'name' => '1 Llave extra',
                'type' => 'extra_key',
                'value' => 1.00,
                'probability' => 30.00,
                'total_quantity' => 50,
                'remaining_quantity' => 50,
            ],
            [
                'name' => '₡5 000 en Billetera',
                'type' => 'wallet_credit',
                'value' => 5000.00,
                'probability' => 20.00,
                'total_quantity' => 20,
                'remaining_quantity' => 20,
            ],
            [
                'name' => 'PlayStation 5',
                'type' => 'physical_prize',
                'value' => 350000.00,
                'probability' => 10.00,
                'total_quantity' => 5,
                'remaining_quantity' => 5,
            ]
        ];

        foreach ($prizes as $prize) {
            \App\Models\ChestPrize::create(array_merge($prize, ['raffle_id' => $raffle1->id]));
            \App\Models\ChestPrize::create(array_merge($prize, ['raffle_id' => $raffle2->id]));
            \App\Models\ChestPrize::create(array_merge($prize, ['raffle_id' => $raffle3->id]));
        }

        // 5. Crear Banners Promocionales de Prueba
        Banner::create([
            'title' => 'GT Coupé 2025',
            'subtitle' => 'Deportivo edición limitada',
            'image_path' => 'https://images.unsplash.com/photo-1503376780353-7e6692767b70?q=80&w=600',
            'action_type' => 'raffle',
            'action_value' => (string)$raffle1->id,
            'is_active' => true,
            'start_date' => now(),
            'end_date' => now()->addDays(30),
            'sort_order' => 1,
        ]);

        Banner::create([
            'title' => 'SUV Black Edition',
            'subtitle' => 'Lujo y potencia',
            'image_path' => 'https://images.unsplash.com/photo-1533473359331-0135ef1b58bf?q=80&w=600',
            'action_type' => 'raffle',
            'action_value' => (string)$raffle2->id,
            'is_active' => true,
            'start_date' => now(),
            'end_date' => now()->addDays(30),
            'sort_order' => 2,
        ]);

        // 6. Crear Historias de Prueba (Instagram / Reels style)
        \App\Models\Story::create([
            'title' => 'Porsche GT 2025',
            'media_path' => 'https://images.unsplash.com/photo-1617814076367-b759c7d7e738?q=80&w=600',
            'media_type' => 'image',
            'button_text' => 'Participar ya',
            'action_type' => 'raffle',
            'action_value' => (string)$raffle1->id,
            'is_active' => true,
            'sort_order' => 1,
        ]);

        \App\Models\Story::create([
            'title' => 'Gran Lanzamiento',
            'media_path' => 'https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4',
            'media_type' => 'video',
            'button_text' => 'Ver SUV Black',
            'action_type' => 'raffle',
            'action_value' => (string)$raffle2->id,
            'is_active' => true,
            'sort_order' => 2,
        ]);

        \App\Models\Story::create([
            'title' => 'Sitio Web Oficial',
            'media_path' => 'https://images.unsplash.com/photo-1511919884226-fd3cad34687c?q=80&w=600',
            'media_type' => 'image',
            'button_text' => 'Visitar Web',
            'action_type' => 'url',
            'action_value' => 'https://wincard.kapix.co.cr/',
            'is_active' => true,
            'sort_order' => 3,
        ]);

        // 7. Sembrar Ajustes de la App por Defecto
        \App\Models\AppSetting::create([
            'wallet_enabled' => true,
            'direct_payment_enabled' => false,
        ]);
    }
}
