<?php

namespace Database\Seeders;

use App\Domains\Authorization\Enums\RoleCode;
use App\Domains\Authorization\Models\Role;
use App\Domains\Menu\Models\Menu;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Database\Seeder;

class MenuSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $menus = [
            ['code' => 'index', 'label' => 'Inicio', 'route' => '/'],
            [
                'code' => 'product.detail',
                'label' => 'Detalle de producto',
                'route' => '/product/:id',
            ],
            ['code' => 'checkout', 'label' => 'Finalizar compra', 'route' => '/checkout'],
            [
                'code' => 'main.adminapp',
                'label' => 'Administración',
                'content_type' => Menu::CONTENT_TYPE_DYNAMIC,
                'route' => '/',
            ],
            ['code' => 'scanner.inicio', 'label' => 'Inicio', 'route' => '/scanner/inicio'],
            ['code' => 'scanner.scan', 'label' => 'Escanear', 'route' => '/scanner/scan'],
            [
                'code' => 'scanner.detail',
                'label' => 'Detalle',
                'route' => '/scanner/detail/:id',
            ],
            [
                'code' => 'adminapp.event',
                'label' => 'Eventos',
                'parent_menu_code' => 'main.adminapp',
                'route' => '/admin/event',
            ],
            [
                'code' => 'adminapp.inicio',
                'label' => 'Inicio',
                'parent_menu_code' => 'main.adminapp',
                'route' => '/admin/inicio',
            ],
            [
                'code' => 'adminapp.catalog',
                'label' => 'Catálogo',
                'parent_menu_code' => 'main.adminapp',
                'route' => '/admin/catalog',
            ],
            [
                'code' => 'adminapp.combos',
                'label' => 'Combos',
                'parent_menu_code' => 'main.adminapp',
                'route' => '/admin/combos',
            ],
            [
                'code' => 'adminapp.categories',
                'label' => 'Categorías',
                'parent_menu_code' => 'main.adminapp',
                'route' => '/admin/categories',
            ],
            [
                'code' => 'adminapp.ventas',
                'label' => 'Ventas',
                'parent_menu_code' => 'main.adminapp',
                'route' => '/admin/ventas',
            ],
            [
                'code' => 'adminapp.staff',
                'label' => 'Staff',
                'parent_menu_code' => 'main.adminapp',
                'route' => '/admin/staff',
            ],
            [
                'code' => 'adminapp.fiesta-futbol-infantil.entradas',
                'label' => 'Entradas',
                'parent_menu_code' => 'main.adminapp',
                'route' => '/admin/entradas',
            ],
            [
                'code' => 'adminapp.fiesta-futbol-infantil.alojamientos',
                'label' => 'Alojamientos',
                'parent_menu_code' => 'main.adminapp',
                'route' => '/admin/alojamientos',
            ],
            [
                'code' => 'adminapp.fiesta-futbol-infantil.merchandising',
                'label' => 'Merchandising',
                'parent_menu_code' => 'main.adminapp',
                'route' => '/admin/merchandising',
            ],
            [
                'code' => 'adminapp.fiesta-futbol-infantil.comida',
                'label' => 'Comida',
                'parent_menu_code' => 'main.adminapp',
                'route' => '/admin/comidas',
            ],
            [
                'code' => 'adminapp.desfile.entradas',
                'label' => 'Entradas',
                'parent_menu_code' => 'main.adminapp',
                'route' => '/admin/desfile/entradas',
            ],
            [
                'code' => 'account',
                'label' => 'Mi cuenta',
                'content_type' => Menu::CONTENT_TYPE_DYNAMIC,
                'route' => '/mi-cuenta',
            ],
            [
                'code' => 'account.profile',
                'label' => 'Datos personales',
                'parent_menu_code' => 'account',
                'route' => '/mi-cuenta/datos-personales',
            ],
            [
                'code' => 'account.purchases',
                'label' => 'Mis compras',
                'parent_menu_code' => 'account',
                'route' => '/mi-cuenta/compras',
            ],
            [
                'code' => 'account.tickets',
                'label' => 'Mis tickets',
                'parent_menu_code' => 'account',
                'route' => '/mi-cuenta/tickets',
            ],
            [
                'code' => 'help',
                'label' => 'Ayuda',
                'content_type' => Menu::CONTENT_TYPE_DYNAMIC,
                'route' => '/ayuda',
            ],
            [
                'code' => 'help.faq',
                'label' => 'Preguntas frecuentes',
                'parent_menu_code' => 'help',
                'content_type' => Menu::CONTENT_TYPE_STATIC,
                'static_content_schema' => [
                    '*.pregunta' => 'required|string',
                    '*.respuesta' => 'required|string',
                    '*.is_active' => 'sometimes|boolean',
                ],
                'route' => '/ayuda/preguntas-frecuentes',
            ],
            [
                'code' => 'help.contact',
                'label' => 'Contacto',
                'parent_menu_code' => 'help',
                'content_type' => Menu::CONTENT_TYPE_STATIC,
                'static_content_schema' => [
                    'whatsapp' => 'required|array',
                    'whatsapp.whatsapp_url' => 'required|url',
                    'whatsapp.whatsapp_label' => 'required|string',
                    'phone' => 'required|string',
                    'locations' => 'required|array|min:1',
                    'locations.*.label' => 'required|string',
                    'locations.*.addresses' => 'required|array|min:1',
                    'locations.*.addresses.*' => 'required|array:label,address,coordinates',
                    'locations.*.addresses.*.label' => 'required|string',
                    'locations.*.addresses.*.address' => 'required|string',
                    'locations.*.addresses.*.coordinates' => 'required|array|size:2',
                    'locations.*.addresses.*.coordinates.0' => 'required|numeric|between:-90,90',
                    'locations.*.addresses.*.coordinates.1' => 'required|numeric|between:-180,180',
                    'map_locations' => 'prohibited',
                ],
                'route' => '/ayuda/contacto',
            ],
            [
                'code' => 'help.payment-methods',
                'label' => 'Medios de pago',
                'parent_menu_code' => 'help',
                'content_type' => Menu::CONTENT_TYPE_DYNAMIC,
                'route' => '/ayuda/medios-de-pago',
            ],
            [
                'code' => 'help.shipping',
                'label' => 'Envíos',
                'parent_menu_code' => 'help',
                'content_type' => Menu::CONTENT_TYPE_DYNAMIC,
                'route' => '/ayuda/envios',
            ],
            [
                'code' => 'help.terms-and-conditions',
                'label' => 'Términos y condiciones',
                'parent_menu_code' => 'help',
                'content_type' => Menu::CONTENT_TYPE_DYNAMIC,
                'route' => '/ayuda/terminos-y-condiciones',
            ],
        ];

        foreach ($menus as $menuData) {
            $menuData = array_merge([
                'parent_menu_code' => null,
                'content_type' => Menu::CONTENT_TYPE_DYNAMIC,
                'static_content_schema' => null,
            ], $menuData);

            Menu::updateOrCreate(['code' => $menuData['code']], $menuData);
        }

        Menu::query()
            ->whereIn('code', ['profile', 'purchases', 'tickets'])
            ->delete();

        Menu::query()
            ->whereIn('code', [
                'admin.event',
                'admin.catalog',
                'admin.combos',
                'admin.categories',
                'admin.ventas',
                'admin.staff',
                'event',
                'catalog',
                'combos',
                'categories',
                'ventas',
                'staff',
            ])
            ->delete();

        $allRoleMenuCodes = Menu::query()->pluck('code');
        $adminAppMenuCodes = Menu::query()
            ->where('code', 'main.adminapp')
            ->orWhere('parent_menu_code', 'main.adminapp')
            ->pluck('code');
        $scannerMenuCodes = Menu::query()
            ->where('code', 'like', 'scanner.%')
            ->pluck('code');
        $userMenuCodes = Menu::query()
            ->whereNotIn('code', $adminAppMenuCodes->merge($scannerMenuCodes))
            ->pluck('code');

        Role::query()
            ->whereIn('codigo', [RoleCode::Admin->value, RoleCode::AdminApp->value])
            ->orderBy('codigo')
            ->each(fn (Role $role) => $role->menus()->sync($allRoleMenuCodes));

        Role::query()
            ->where('codigo', RoleCode::User->value)
            ->orderBy('codigo')
            ->each(fn (Role $role) => $role->menus()->sync($userMenuCodes));

        Role::query()
            ->where('codigo', RoleCode::Scanner->value)
            ->orderBy('codigo')
            ->each(fn (Role $role) => $role->menus()->sync($scannerMenuCodes));

        $tenants = Tenant::all();

        $allMenus = Menu::pluck('code')->toArray();
        $helpMenuCodes = [
            'help',
            'help.faq',
            'help.contact',
            'help.payment-methods',
            'help.shipping',
            'help.terms-and-conditions',
        ];
        $helpTenantCodes = [
            'sonder',
            'fiesta_futbol_infantil',
        ];
        $fiestaCategoryMenuCodes = [
            'adminapp.fiesta-futbol-infantil.entradas',
            'adminapp.fiesta-futbol-infantil.alojamientos',
            'adminapp.fiesta-futbol-infantil.merchandising',
            'adminapp.fiesta-futbol-infantil.comida',
        ];
        $fiestaExcludedAdminMenuCodes = [
            'adminapp.inicio',
            'adminapp.catalog',
            'adminapp.categories',
            'adminapp.combos',
        ];
        $desfileMenuCodes = [
            'adminapp.desfile.entradas',
        ];
        $frequentlyAskedQuestions = [
            [
                'pregunta' => '¿Hay algún límite de compra?',
                'respuesta' => 'No hay un límite general de compra. La cantidad disponible depende del stock de cada producto.',
                'is_active' => true,
            ],
            [
                'pregunta' => '¿Cuáles son los medios de pago disponibles?',
                'respuesta' => 'Podés consultar y seleccionar los medios de pago habilitados al momento de finalizar tu compra.',
                'is_active' => false,
            ],
            [
                'pregunta' => 'Necesito asesoramiento antes de comprar el producto, ¿cómo puedo hacer?',
                'respuesta' => 'Nuestro equipo comercial está preparado para asesorarte, no dudes en escribirnos por WhatsApp al (0341) 6658247 de lunes a viernes de 8.30 a 20 horas. Los sábados, domingos y feriados te contestaremos lo más rápido posible.',
                'is_active' => false,
            ],
        ];
        $contactContent = [
            'whatsapp' => [
                'whatsapp_url' => 'https://wa.me/543412602222',
                'whatsapp_label' => 'Chatea con nosotros',
            ],
            'phone' => '+54 9 (0341) 6658247',
            'locations' => [
                'rosario' => [
                    'label' => 'Rosario',
                    'addresses' => [
                        [
                            'label' => 'Gigante de Arroyito',
                            'address' => 'Av. Génova 640, Rosario',
                            'coordinates' => [-32.913997, -60.674567],
                        ],
                        [
                            'label' => 'Telepagos',
                            'address' => 'Rioja 1150, piso 12, dpto. 3, Rosario',
                            'coordinates' => [-32.946820, -60.639320],
                        ],
                    ],
                ],
            ],
        ];

        foreach ($tenants as $tenant) {
            $menuCodes = $allMenus;

            if ($tenant->codigo === 'sonder') {
                // Sonder NO tiene tickets
                $menuCodes = array_diff($menuCodes, ['account.tickets']);
            } else {
                // Los demás NO tienen product.detail
                $menuCodes = array_diff($menuCodes, ['product.detail']);
            }

            if (! in_array($tenant->codigo, $helpTenantCodes, true)) {
                $menuCodes = array_diff($menuCodes, $helpMenuCodes);
            }

            if ($tenant->codigo !== 'fiesta_futbol_infantil') {
                $menuCodes = array_diff($menuCodes, $fiestaCategoryMenuCodes);
            } else {
                $menuCodes = array_diff($menuCodes, $fiestaExcludedAdminMenuCodes);
            }

            if ($tenant->codigo !== 'desfile_pura_tendencia') {
                $menuCodes = array_diff($menuCodes, $desfileMenuCodes);
            }

            // Usar sync para asociar los menues al tenant
            $tenant->menues()->sync($menuCodes);

            if (in_array($tenant->codigo, $helpTenantCodes, true)) {
                $tenant->menues()->updateExistingPivot('help.faq', [
                    'static_content' => $frequentlyAskedQuestions,
                ]);
                $tenant->menues()->updateExistingPivot('help.contact', [
                    'static_content' => $contactContent,
                ]);
            }
        }
    }
}
