<?php

namespace Tests\Feature\Tenant;

use App\Domains\Attachable\Enums\AttachmentType;
use App\Domains\Attachable\Models\Attachment;
use App\Domains\Attachable\Models\AttachmentCrop;
use App\Domains\Authorization\Enums\RoleCode;
use App\Domains\Authorization\Models\Role;
use App\Domains\Catalog\Models\Category;
use App\Domains\Menu\Models\Menu;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Tenant\Models\WebsiteType;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Tests\TestCase;

class BootstrapTenantControllerTest extends TestCase
{
    use RefreshDatabase;

    public function test_it_bootstraps_a_tenant_by_domain(): void
    {
        $hdrKey = (string) Str::uuid();
        $ftrKey = (string) Str::uuid();

        $headerAttachment = Attachment::create([
            'key' => $hdrKey,
            'path' => 'tenants/'.$hdrKey.'.png',
            'filename' => 'logo_header.png',
            'type' => AttachmentType::Image,
            'mime_type' => 'image/png',
        ]);
        $footerAttachment = Attachment::create([
            'key' => $ftrKey,
            'path' => 'tenants/'.$ftrKey.'.png',
            'filename' => 'logo_footer.png',
            'type' => AttachmentType::Image,
            'mime_type' => 'image/png',
        ]);
        $headerBackgroundAttachment = Attachment::create([
            'key' => (string) Str::uuid(),
            'path' => 'tenants/header-background.png',
            'filename' => 'header-background.png',
            'type' => AttachmentType::Image,
            'mime_type' => 'image/png',
        ]);
        $footerBackgroundAttachment = Attachment::create([
            'key' => (string) Str::uuid(),
            'path' => 'tenants/footer-background.png',
            'filename' => 'footer-background.png',
            'type' => AttachmentType::Image,
            'mime_type' => 'image/png',
        ]);

        $tenant = Tenant::create([
            'codigo' => 'acme',
            'nombre' => 'Acme',
            'dominio' => 'acme.com',
            'address' => 'Calle Test 123, Rosario',
            'phone' => '+54 341 555 1234',
            'primary_color' => '#ff0000',
            'secondary_color' => '#00ff00',
            'danger_color' => '#0000ff',
            'success_color' => '#00ff00',
            'header_bg_color' => '#ffffff',
            'footer_bg_color' => '#ffffff',
            'header_logo_id' => $headerAttachment->id,
            'footer_logo_id' => $footerAttachment->id,
            'header_bg_image_id' => $headerBackgroundAttachment->id,
            'footer_bg_image_id' => $footerBackgroundAttachment->id,
            'event_date_text' => '9, 10, 11 y 12 de Octubre 2026',
            'display_categories' => false,
            'display_seach_bar' => false,
            'display_cart' => false,
            'cart_editing_policy' => 'disabled',
            'checkout_editing_policy' => 'disabled',
            'display_cart_item_images' => false,
        ]);

        $response = $this->getJson('/api/tenants/bootstrap?dominio=acme.com&path=%2F');

        $response
            ->assertOk()
            ->assertJsonPath('data.codigo', 'acme')
            ->assertJsonPath('data.dominio', 'acme.com')
            ->assertJsonPath('data.address', 'Calle Test 123, Rosario')
            ->assertJsonPath('data.phone', '+54 341 555 1234')
            ->assertJsonPath('data.primary_color', '#ff0000')
            ->assertJsonPath('data.secondary_color', '#00ff00')
            ->assertJsonPath('data.danger_color', '#0000ff')
            ->assertJsonPath('data.success_color', '#00ff00')
            ->assertJsonPath('data.event_date_text', '9, 10, 11 y 12 de Octubre 2026')
            ->assertJsonPath('data.display_categories', false)
            ->assertJsonPath('data.display_seach_bar', false)
            ->assertJsonPath('data.display_cart', false)
            ->assertJsonPath('data.cart_editing_policy.code', 'disabled')
            ->assertJsonPath('data.cart_editing_policy.allow_modify', false)
            ->assertJsonPath('data.cart_editing_policy.allow_delete', false)
            ->assertJsonPath('data.cart_editing_policy.allow_update_quantity', false)
            ->assertJsonPath('data.cart_editing_policy.allow_update_variant', false)
            ->assertJsonPath('data.checkout_editing_policy.code', 'disabled')
            ->assertJsonPath('data.checkout_editing_policy.allow_modify', false)
            ->assertJsonPath('data.checkout_editing_policy.allow_delete', false)
            ->assertJsonPath('data.checkout_editing_policy.allow_update_quantity', false)
            ->assertJsonPath('data.checkout_editing_policy.allow_update_variant', false)
            ->assertJsonPath('data.display_cart_item_images', false)
            ->assertJsonPath('data.header_bg_color', '#ffffff')->assertJsonPath('data.footer_bg_color', '#ffffff');

        $headerUrl = $response->json('data.header_logo');
        $footerUrl = $response->json('data.footer_logo');
        $headerBackgroundUrl = $response->json('data.header_bg_image');
        $footerBackgroundUrl = $response->json('data.footer_bg_image');

        $this->assertStringContainsString($headerAttachment->key, $headerUrl);
        $this->assertStringContainsString($footerAttachment->key, $footerUrl);
        $this->assertStringContainsString($headerBackgroundAttachment->key, $headerBackgroundUrl);
        $this->assertStringContainsString($footerBackgroundAttachment->key, $footerBackgroundUrl);
        $this->assertTrue(
            str_contains($headerUrl, 'Expires=') || str_contains($headerUrl, 'expiration=') || str_contains($headerUrl, 'X-Amz-Expires=')
        );
        $this->assertTrue(
            str_contains($footerUrl, 'Expires=') || str_contains($footerUrl, 'expiration=') || str_contains($footerUrl, 'X-Amz-Expires=')
        );

        $this->assertArrayNotHasKey('props', $response->json('data'));
    }

    public function test_it_bootstraps_a_tenant_from_a_full_url(): void
    {
        $this->createTenant([
            'codigo' => 'acme',
            'nombre' => 'Acme',
            'dominio' => 'acme.com',
        ]);

        $encodedDomain = urlencode('https://ACME.com:8080');

        $response = $this->getJson("/api/tenants/bootstrap?dominio={$encodedDomain}&path=%2F");

        $response
            ->assertOk()
            ->assertJsonPath('data.codigo', 'acme')
            ->assertJsonPath('data.dominio', 'acme.com');
    }

    public function test_it_resolves_the_longest_tenant_prefix_for_deep_links(): void
    {
        $this->createTenant([
            'codigo' => 'qa-root',
            'nombre' => 'QA Root',
            'dominio' => 'qa.onticket.com.ar',
        ]);
        $this->createTenant([
            'codigo' => 'pura-tendencia',
            'nombre' => 'Pura Tendencia',
            'dominio' => 'qa.onticket.com.ar',
            'base_path' => '/puratendencia',
        ]);
        $this->createTenant([
            'codigo' => 'pura-tendencia-vip',
            'nombre' => 'Pura Tendencia VIP',
            'dominio' => 'qa.onticket.com.ar',
            'base_path' => '/puratendencia/vip',
        ]);

        $this->getJson('/api/tenants/bootstrap?dominio=qa.onticket.com.ar&path=%2Fpuratendencia%2Fproductos%2F123')
            ->assertOk()
            ->assertJsonPath('data.codigo', 'pura-tendencia')
            ->assertJsonPath('data.dominio', 'qa.onticket.com.ar')
            ->assertJsonPath('data.base_path', '/puratendencia');

        $this->getJson('/api/tenants/bootstrap?dominio=qa.onticket.com.ar&path=%2Fpuratendencia%2Fvip%2Fproductos%2F123')
            ->assertOk()
            ->assertJsonPath('data.codigo', 'pura-tendencia-vip')
            ->assertJsonPath('data.dominio', 'qa.onticket.com.ar')
            ->assertJsonPath('data.base_path', '/puratendencia/vip');
    }

    public function test_it_uses_the_root_tenant_for_spa_paths_without_a_tenant_prefix(): void
    {
        $this->createTenant([
            'codigo' => 'qa-root',
            'nombre' => 'QA Root',
            'dominio' => 'qa.onticket.com.ar',
        ]);
        $this->createTenant([
            'codigo' => 'sonder',
            'nombre' => 'Sonder',
            'dominio' => 'qa.onticket.com.ar',
            'base_path' => '/sonder',
        ]);

        $this->getJson('/api/tenants/bootstrap?dominio=qa.onticket.com.ar&path=%2Fproducto%2F123')
            ->assertOk()
            ->assertJsonPath('data.codigo', 'qa-root');

        $this->getJson('/api/tenants/bootstrap?dominio=qa.onticket.com.ar&path=%2Fsonder-shop%2Fproducto%2F123')
            ->assertOk()
            ->assertJsonPath('data.codigo', 'qa-root');
    }

    public function test_the_legacy_bootstrap_route_is_not_available(): void
    {
        $this->getJson('/api/tenants/bootstrap/acme.com')->assertNotFound();
    }

    public function test_it_resolves_browser_branding_from_the_tenant_before_the_website_type(): void
    {
        $typeFavicon = Attachment::query()->create([
            'key' => (string) Str::uuid(),
            'path' => 'website-types/type-favicon.png',
            'filename' => 'type-favicon.png',
            'type' => AttachmentType::Image,
            'mime_type' => 'image/png',
        ]);
        $tenantFavicon = Attachment::query()->create([
            'key' => (string) Str::uuid(),
            'path' => 'tenants/tenant-favicon.png',
            'filename' => 'tenant-favicon.png',
            'type' => AttachmentType::Image,
            'mime_type' => 'image/png',
        ]);
        $websiteType = WebsiteType::query()->create([
            'codigo' => 'store',
            'nombre' => 'Tienda',
            'site_title' => 'Website type title',
            'favicon_id' => $typeFavicon->id,
        ]);
        $tenant = $this->createTenant([
            'website_type_code' => $websiteType->codigo,
        ]);

        $typeResponse = $this->getJson('/api/tenants/bootstrap?dominio=acme.com&path=%2F');

        $typeResponse
            ->assertOk()
            ->assertJsonPath('data.site_title', 'Website type title');
        $this->assertStringContainsString($typeFavicon->key, $typeResponse->json('data.favicon'));

        $tenant->update([
            'site_title' => 'Tenant title',
            'favicon_id' => $tenantFavicon->id,
        ]);

        $tenantResponse = $this->getJson('/api/tenants/bootstrap?dominio=acme.com&path=%2F');

        $tenantResponse
            ->assertOk()
            ->assertJsonPath('data.site_title', 'Tenant title');
        $this->assertStringContainsString($tenantFavicon->key, $tenantResponse->json('data.favicon'));
    }

    public function test_it_uses_default_browser_branding_when_none_is_configured(): void
    {
        $this->createTenant();

        $this->getJson('/api/tenants/bootstrap?dominio=acme.com&path=%2F')
            ->assertOk()
            ->assertJsonPath('data.site_title', 'ShopitFront')
            ->assertJsonPath('data.favicon', null);
    }

    public function test_it_returns_only_the_tenant_categories_in_the_bootstrap(): void
    {
        $tenant = $this->createTenant();
        $otherTenant = $this->createTenant([
            'codigo' => 'globex',
            'nombre' => 'Globex',
            'dominio' => 'globex.com',
        ]);

        $parent = Category::query()->create([
            'tenant_code' => $tenant->codigo,
            'nombre' => 'Remeras',
        ]);
        Category::query()->create([
            'tenant_code' => $tenant->codigo,
            'categoria_id' => $parent->id,
            'nombre' => 'Manga corta',
        ]);
        Category::query()->create([
            'tenant_code' => $otherTenant->codigo,
            'nombre' => 'Otra categoría',
        ]);
        Category::query()->create([
            'tenant_code' => null,
            'nombre' => 'Global',
        ]);

        $this->getJson('/api/tenants/bootstrap?dominio=acme.com&path=%2F')
            ->assertOk()
            ->assertJsonCount(1, 'data.categories')
            ->assertJsonPath('data.categories.0.nombre', 'Remeras')
            ->assertJsonCount(1, 'data.categories.0.subcategories')
            ->assertJsonPath('data.categories.0.subcategories.0.nombre', 'Manga corta')
            ->assertJsonPath('data.categories.0.subcategories.0.subcategories', [])
            ->assertJsonMissingPath('data.categories.0.categoria_id')
            ->assertJsonMissing(['nombre' => 'Otra categoría'])
            ->assertJsonMissing(['nombre' => 'Global']);
    }

    public function test_it_returns_only_enabled_website_extras_in_the_bootstrap(): void
    {
        $tenant = $this->createTenant();
        $websiteType = WebsiteType::query()->create([
            'codigo' => 'store',
            'nombre' => 'Tienda',
        ]);
        $tenant->update(['website_type_code' => $websiteType->codigo]);

        $enabledExtra = $websiteType->extras()->create([
            'codigo' => 'contact',
            'nombre' => 'Contacto',
            'descripcion' => 'Datos de contacto.',
            'config_schema' => [],
        ]);
        $disabledExtra = $websiteType->extras()->create([
            'codigo' => 'banner',
            'nombre' => 'Banner',
            'descripcion' => 'Banner promocional.',
            'config_schema' => [],
        ]);
        $tenant->websiteExtras()->create([
            'website_type_extra_id' => $enabledExtra->id,
            'config' => ['phone' => '+54 341 555 0101'],
            'is_enabled' => true,
        ]);
        $tenant->websiteExtras()->create([
            'website_type_extra_id' => $disabledExtra->id,
            'config' => ['title' => 'No mostrar'],
            'is_enabled' => false,
        ]);

        $this->getJson('/api/tenants/bootstrap?dominio=acme.com&path=%2F')
            ->assertOk()
            ->assertJsonMissingPath('data.website_type')
            ->assertJsonPath('data.extras.contact.phone', '+54 341 555 0101')
            ->assertJsonMissingPath('data.extras.banner');
    }

    public function test_the_bootstrap_returns_only_the_cropped_banner_url(): void
    {
        Storage::fake('s3');
        $tenant = $this->createTenant();
        $websiteType = WebsiteType::query()->create([
            'codigo' => 'event-store',
            'nombre' => 'Eventos',
        ]);
        $tenant->update(['website_type_code' => $websiteType->codigo]);
        $heroDefinition = $websiteType->extras()->create([
            'codigo' => 'heroConfig',
            'nombre' => 'Banner',
            'config_schema' => [
                'transforms' => [
                    'background_image_id' => [
                        'handler' => 'attachment',
                        'attachment_type' => 'image',
                    ],
                ],
            ],
        ]);
        $desktop = Attachment::query()->create([
            'key' => (string) Str::uuid(),
            'path' => 'tenants/acme/desktop.jpg',
            'filename' => 'desktop.jpg',
            'type' => AttachmentType::Image,
            'mime_type' => 'image/jpeg',
            'extension' => 'jpg',
        ]);
        $mobile = Attachment::query()->create([
            'key' => (string) Str::uuid(),
            'path' => 'tenants/acme/mobile.jpg',
            'filename' => 'mobile.jpg',
            'type' => AttachmentType::Image,
            'mime_type' => 'image/jpeg',
            'extension' => 'jpg',
        ]);
        $original = Attachment::query()->create([
            'key' => (string) Str::uuid(),
            'path' => 'tenants/acme/original.jpg',
            'filename' => 'original.jpg',
            'type' => AttachmentType::Image,
            'mime_type' => 'image/jpeg',
            'extension' => 'jpg',
        ]);
        foreach ([AttachmentCrop::DESKTOP => $desktop, AttachmentCrop::MOBILE => $mobile] as $variant => $crop) {
            $original->cropVariants()->create([
                'variant' => $variant,
                'crop_horizontal' => ['start_percentage' => 10, 'end_percentage' => 90],
                'crop_vertical' => ['start_percentage' => 20, 'end_percentage' => 80],
                'cropped_attachment_id' => $crop->id,
            ]);
        }
        $tenant->websiteExtras()->create([
            'website_type_extra_id' => $heroDefinition->id,
            'config' => ['background_image_id' => $original->id],
            'is_enabled' => true,
        ]);

        $response = $this->getJson('/api/tenants/bootstrap?dominio=acme.com&path=%2F')
            ->assertOk()
            ->assertJsonMissingPath('data.extras.heroConfig.crop_horizontal')
            ->assertJsonMissingPath('data.extras.heroConfig.crop_vertical');

        $response
            ->assertJsonPath('data.extras.heroConfig.background_image_id.desktop', fn (string $url): bool => str_contains($url, 'desktop.jpg'))
            ->assertJsonPath('data.extras.heroConfig.background_image_id.mobile', fn (string $url): bool => str_contains($url, 'mobile.jpg'));
    }

    public function test_it_returns_not_found_when_the_domain_does_not_exist(): void
    {
        $response = $this->getJson('/api/tenants/bootstrap?dominio=missing.example&path=%2F');

        $response->assertNotFound();
    }

    public function test_it_returns_tenant_menus_as_a_clean_hierarchy(): void
    {
        $tenant = $this->createTenant();
        $userRole = Role::query()->create([
            'codigo' => RoleCode::User->value,
            'nombre' => 'Usuario',
        ]);
        $parent = Menu::query()->create([
            'code' => 'help',
            'label' => 'Ayuda',
            'content_type' => Menu::CONTENT_TYPE_DYNAMIC,
            'route' => '/ayuda',
        ]);
        $staticChild = Menu::query()->create([
            'code' => 'help.faq',
            'label' => 'Preguntas frecuentes',
            'parent_menu_code' => $parent->code,
            'content_type' => Menu::CONTENT_TYPE_STATIC,
            'static_content_schema' => [
                '*.question' => 'required|string',
                '*.answer' => 'required|string',
            ],
            'route' => '/ayuda/preguntas-frecuentes',
        ]);
        $dynamicChild = Menu::query()->create([
            'code' => 'help.shipping',
            'label' => 'Envíos',
            'parent_menu_code' => $parent->code,
            'content_type' => Menu::CONTENT_TYPE_DYNAMIC,
            'route' => '/ayuda/envios',
        ]);
        $staticContent = [
            [
                'question' => '¿Cómo compro?',
                'answer' => 'Desde el catálogo.',
            ],
        ];

        $tenant->menues()->sync([
            $parent->code,
            $staticChild->code => ['static_content' => $staticContent],
            $dynamicChild->code,
        ]);
        $userRole->menus()->sync([
            $parent->code,
            $staticChild->code,
            $dynamicChild->code,
        ]);

        $response = $this->getJson('/api/tenants/bootstrap?dominio=acme.com&path=%2F');

        $response
            ->assertOk()
            ->assertJsonCount(1, 'data.menues')
            ->assertJsonCount(2, 'data.menues.0.submenues')
            ->assertJsonPath('data.menues.0.code', 'help')
            ->assertJsonPath('data.menues.0.label', 'Ayuda')
            ->assertJsonPath('data.menues.0.parent_menu_code', null)
            ->assertJsonPath('data.menues.0.submenues.0.code', 'help.shipping')
            ->assertJsonPath('data.menues.0.submenues.0.label', 'Envíos')
            ->assertJsonPath('data.menues.0.submenues.0.parent_menu_code', 'help')
            ->assertJsonPath('data.menues.0.submenues.1.code', 'help.faq');

        $assertCleanMenu = function (array $menu) use (&$assertCleanMenu): void {
            $this->assertArrayNotHasKey('created_at', $menu);
            $this->assertArrayNotHasKey('updated_at', $menu);
            $this->assertArrayNotHasKey('pivot', $menu);
            $this->assertArrayNotHasKey('static_content_schema', $menu);

            foreach ($menu['submenues'] as $submenu) {
                $assertCleanMenu($submenu);
            }
        };

        $menus = $response->json('data.menues');
        $this->assertEquals($staticContent, $menus[0]['submenues'][1]['static_content']);
        $assertCleanMenu($menus[0]);
        $this->assertArrayNotHasKey('static_content', $menus[0]);
        $this->assertArrayNotHasKey('static_content', $menus[0]['submenues'][0]);
    }

    public function test_it_returns_only_menus_assigned_to_the_user_role(): void
    {
        $tenant = $this->createTenant();
        $userRole = Role::query()->create([
            'codigo' => RoleCode::User->value,
            'nombre' => 'Usuario',
        ]);
        $adminRole = Role::query()->create([
            'codigo' => RoleCode::Admin->value,
            'nombre' => 'Administrador',
        ]);
        $userMenu = Menu::query()->create([
            'code' => 'account',
            'label' => 'Mi cuenta',
            'route' => '/mi-cuenta',
        ]);
        $adminMenu = Menu::query()->create([
            'code' => 'admin.catalog',
            'label' => 'Catálogo',
            'route' => '/admin/catalog',
        ]);

        $tenant->menues()->sync([$userMenu->code, $adminMenu->code]);
        $userRole->menus()->sync([$userMenu->code]);
        $adminRole->menus()->sync([$adminMenu->code]);

        $this->getJson('/api/tenants/bootstrap?dominio=acme.com&path=%2F')
            ->assertOk()
            ->assertJsonPath('data.menues.0.code', 'account')
            ->assertJsonMissing(['code' => 'admin.catalog']);
    }

    public function test_it_orders_parent_menus_and_their_submenus_by_label(): void
    {
        $tenant = $this->createTenant();
        $userRole = Role::query()->create([
            'codigo' => RoleCode::User->value,
            'nombre' => 'Usuario',
        ]);

        $zeta = Menu::query()->create([
            'code' => 'zeta',
            'label' => 'Zeta',
            'route' => '/zeta',
        ]);
        $tree = Menu::query()->create([
            'code' => 'tree',
            'label' => 'Árbol',
            'route' => '/arbol',
        ]);
        $fox = Menu::query()->create([
            'code' => 'tree.fox',
            'label' => 'Zorro',
            'parent_menu_code' => $tree->code,
            'route' => '/arbol/zorro',
        ]);
        $eagle = Menu::query()->create([
            'code' => 'tree.eagle',
            'label' => 'Águila',
            'parent_menu_code' => $tree->code,
            'route' => '/arbol/aguila',
        ]);

        $menuCodes = [$zeta->code, $tree->code, $fox->code, $eagle->code];
        $tenant->menues()->sync($menuCodes);
        $userRole->menus()->sync($menuCodes);

        $this->getJson('/api/tenants/bootstrap?dominio=acme.com&path=%2F')
            ->assertOk()
            ->assertJsonPath('data.menues.0.code', 'tree')
            ->assertJsonPath('data.menues.1.code', 'zeta')
            ->assertJsonPath('data.menues.0.submenues.0.code', 'tree.eagle')
            ->assertJsonPath('data.menues.0.submenues.1.code', 'tree.fox');
    }

    private function createTenant(array $attributes = []): Tenant
    {
        $hdrKey = (string) Str::uuid();
        $ftrKey = (string) Str::uuid();

        $headerAttachment = Attachment::create([
            'key' => $hdrKey,
            'path' => 'tenants/'.$hdrKey.'.png',
            'filename' => 'logo_header.png',
            'type' => AttachmentType::Image,
            'mime_type' => 'image/png',
        ]);
        $footerAttachment = Attachment::create([
            'key' => $ftrKey,
            'path' => 'tenants/'.$ftrKey.'.png',
            'filename' => 'logo_footer.png',
            'type' => AttachmentType::Image,
            'mime_type' => 'image/png',
        ]);

        return Tenant::create(array_merge([
            'codigo' => 'acme',
            'nombre' => 'Acme',
            'dominio' => 'acme.com',
            'primary_color' => '#ff0000',
            'secondary_color' => '#00ff00',
            'danger_color' => '#0000ff',
            'success_color' => '#00ff00',
            'header_bg_color' => '#ffffff',
            'footer_bg_color' => '#ffffff',
            'header_logo_id' => $headerAttachment->id,
            'footer_logo_id' => $footerAttachment->id,
        ], $attributes));
    }

}
