<?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');
    }

    public function test_it_allows_different_domain_paths_and_rejects_duplicate_tenant_keys(): void
    {
        $base64Image = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==';

        $firstResponse = $this->postJson('/api/tenants', [
            'codigo' => 'acme',
            'nombre' => 'Acme',
            'dominio' => 'https://ACME.com/puratendencia/',
            'primary_color' => '#111111',
            'secondary_color' => '#222222',
            'danger_color' => '#333333',
            'success_color' => '#555555',
            'header_bg_color' => '#444444',
            'footer_bg_color' => '#444444',
            'header_logo' => $base64Image,
            'footer_logo' => $base64Image,
        ]);

        $firstResponse
            ->assertCreated()
            ->assertJsonPath('data.dominio', 'acme.com')
            ->assertJsonPath('data.base_path', '/puratendencia')
            ->assertJsonPath('data.primary_color', '#111111')
            ->assertJsonPath('data.secondary_color', '#222222')
            ->assertJsonPath('data.danger_color', '#333333')
            ->assertJsonPath('data.success_color', '#555555')
            ->assertJsonPath('data.header_bg_color', '#444444')->assertJsonPath('data.footer_bg_color', '#444444');

        $tenant = Tenant::query()->with(['headerLogo', 'footerLogo'])->where('codigo', 'acme')->firstOrFail();

        $this->assertNotNull($tenant->header_logo_id);
        $this->assertNotNull($tenant->footer_logo_id);

        $this->assertDatabaseHas('tenants', [
            'codigo' => 'acme',
            'primary_color' => '#111111',
            'secondary_color' => '#222222',
            'danger_color' => '#333333',
            'success_color' => '#555555',
            'header_bg_color' => '#444444',
            'footer_bg_color' => '#444444',
            'header_logo_id' => $tenant->header_logo_id,
            'footer_logo_id' => $tenant->footer_logo_id,
        ]);

        $headerUrl = $firstResponse->json('data.header_logo');
        $footerUrl = $firstResponse->json('data.footer_logo');

        $this->assertStringContainsString($tenant->headerLogo->key, $headerUrl);
        $this->assertStringContainsString($tenant->footerLogo->key, $footerUrl);
        $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=')
        );

        $differentPathResponse = $this->postJson('/api/tenants', [
            'codigo' => 'pura-tendencia',
            'nombre' => 'Pura Tendencia',
            'dominio' => 'acme.com',
            'base_path' => '/sonder/',
            'primary_color' => '#111111',
            'secondary_color' => '#222222',
            'danger_color' => '#333333',
            'success_color' => '#555555',
            'header_bg_color' => '#444444',
            'footer_bg_color' => '#444444',
            'header_logo' => $base64Image,
            'footer_logo' => $base64Image,
        ]);

        $differentPathResponse
            ->assertCreated()
            ->assertJsonPath('data.dominio', 'acme.com')
            ->assertJsonPath('data.base_path', '/sonder');

        $secondResponse = $this->postJson('/api/tenants', [
            'codigo' => 'globex',
            'nombre' => 'Globex',
            'dominio' => 'acme.com',
            'base_path' => '/puratendencia',
            'primary_color' => '#111111',
            'secondary_color' => '#222222',
            'danger_color' => '#333333',
            'success_color' => '#555555',
            'header_bg_color' => '#444444',
            'footer_bg_color' => '#444444',
            'header_logo' => (string) Str::uuid(),
            'footer_logo' => (string) Str::uuid(),
        ]);

        $secondResponse
            ->assertUnprocessable()
            ->assertJsonValidationErrors(['dominio']);
    }

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

        $otherTenant = $this->createTenant([
            'codigo' => 'globex',
            'nombre' => 'Globex',
            'dominio' => 'globex.com',
        ]);

        $hdrUuid = (string) Str::uuid();
        $ftrUuid = (string) Str::uuid();

        $hdrAttachment = Attachment::create([
            'key' => $hdrUuid,
            'path' => 'tenants/'.$hdrUuid.'.png',
            'filename' => 'hdr.png',
            'type' => AttachmentType::Image,
            'mime_type' => 'image/png',
        ]);
        $ftrAttachment = Attachment::create([
            'key' => $ftrUuid,
            'path' => 'tenants/'.$ftrUuid.'.png',
            'filename' => 'ftr.png',
            'type' => AttachmentType::Image,
            'mime_type' => 'image/png',
        ]);

        $successfulResponse = $this->putJson("/api/tenants/{$tenant->codigo}", [
            'codigo' => 'acme',
            'nombre' => 'Acme Updated',
            'dominio' => 'https://ACME.com:443/',
            'primary_color' => '#555555',
            'secondary_color' => '#666666',
            'danger_color' => '#777777',
            'success_color' => '#999999',
            'header_bg_color' => '#888888',
            'footer_bg_color' => '#888888',
            'header_logo' => $hdrUuid,
            'footer_logo' => $ftrUuid,
        ]);

        $successfulResponse
            ->assertOk()
            ->assertJsonPath('data.nombre', 'Acme Updated')
            ->assertJsonPath('data.dominio', 'acme.com')
            ->assertJsonPath('data.primary_color', '#555555')
            ->assertJsonPath('data.secondary_color', '#666666')
            ->assertJsonPath('data.danger_color', '#777777')
            ->assertJsonPath('data.success_color', '#999999')
            ->assertJsonPath('data.header_bg_color', '#888888')->assertJsonPath('data.footer_bg_color', '#888888');

        $headerUrl = $successfulResponse->json('data.header_logo');
        $footerUrl = $successfulResponse->json('data.footer_logo');

        $this->assertStringContainsString($hdrUuid, $headerUrl);
        $this->assertStringContainsString($ftrUuid, $footerUrl);
        $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->assertDatabaseHas('tenants', [
            'id' => $tenant->id,
            'primary_color' => '#555555',
            'secondary_color' => '#666666',
            'danger_color' => '#777777',
            'success_color' => '#999999',
            'header_bg_color' => '#888888',
            'footer_bg_color' => '#888888',
            'header_logo_id' => $hdrAttachment->id,
            'footer_logo_id' => $ftrAttachment->id,
        ]);

        $failingResponse = $this->putJson("/api/tenants/{$otherTenant->codigo}", [
            'codigo' => 'globex',
            'nombre' => 'Globex',
            'dominio' => 'https://ACME.com/',
        ]);

        $failingResponse
            ->assertUnprocessable()
            ->assertJsonValidationErrors(['dominio']);
    }

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

        $response = $this->putJson("/api/tenants/{$tenant->codigo}", [
            'primary_color' => '#000000',
            'cart_editing_policy' => 'quantity_and_remove',
            'checkout_editing_policy' => 'disabled',
            'display_cart_item_images' => false,
        ]);

        $response
            ->assertOk()
            ->assertJsonPath('data.codigo', 'acme')
            ->assertJsonPath('data.nombre', 'Acme')
            ->assertJsonPath('data.primary_color', '#000000')
            ->assertJsonPath('data.cart_editing_policy.code', 'quantity_and_remove')
            ->assertJsonPath('data.cart_editing_policy.allow_modify', true)
            ->assertJsonPath('data.cart_editing_policy.allow_delete', true)
            ->assertJsonPath('data.cart_editing_policy.allow_update_quantity', true)
            ->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.display_cart_item_images', false);

        $this->assertDatabaseHas('tenants', [
            'id' => $tenant->id,
            'codigo' => 'acme',
            'nombre' => 'Acme',
            'primary_color' => '#000000',
            'cart_editing_policy' => 'quantity_and_remove',
            'checkout_editing_policy' => 'disabled',
            'display_cart_item_images' => false,
        ]);
    }

    public function test_it_validates_aesthetic_colors(): void
    {
        $response = $this->postJson('/api/tenants', [
            'codigo' => 'acme',
            'nombre' => 'Acme',
            'dominio' => 'acme.com',
            'primary_color' => 'invalid-color',
            'secondary_color' => '#222222',
            'danger_color' => '#333333',
            'success_color' => '#555555',
            'header_bg_color' => '#444444',
            'footer_bg_color' => '#444444',
            'header_logo' => (string) Str::uuid(),
            'footer_logo' => (string) Str::uuid(),
        ]);

        $response->assertJsonValidationErrors(['primary_color']);

        $response2 = $this->postJson('/api/tenants', [
            'codigo' => 'acme',
            'nombre' => 'Acme',
            'dominio' => 'acme.com',
            'primary_color' => '#12345',
            'secondary_color' => '#222222',
            'danger_color' => '#333333',
            'success_color' => '#555555',
            'header_bg_color' => '#444444',
            'footer_bg_color' => '#444444',
            'header_logo' => (string) Str::uuid(),
            'footer_logo' => (string) Str::uuid(),
        ]);

        $response2->assertJsonValidationErrors(['primary_color']);

        $response3 = $this->postJson('/api/tenants', [
            'codigo' => 'acme',
            'nombre' => 'Acme',
            'dominio' => 'acme.com',
            'primary_color' => '#111111',
            'secondary_color' => '#222222',
            'danger_color' => '#333333',
            'success_color' => 'invalid-color',
            'header_bg_color' => '#444444',
            'footer_bg_color' => '#444444',
            'header_logo' => (string) Str::uuid(),
            'footer_logo' => (string) Str::uuid(),
        ]);

        $response3->assertJsonValidationErrors(['success_color']);
    }

    public function test_it_validates_logo_must_be_image_or_svg(): void
    {
        Storage::fake('s3');

        $response = $this->postJson('/api/tenants', [
            'codigo' => 'acme',
            'nombre' => 'Acme',
            'dominio' => 'acme.com',
            'primary_color' => '#111111',
            'secondary_color' => '#222222',
            'danger_color' => '#333333',
            'success_color' => '#555555',
            'header_bg_color' => '#444444',
            'footer_bg_color' => '#444444',
            'header_logo' => UploadedFile::fake()->create('document.pdf', 10, 'application/pdf'),
            'footer_logo' => (string) Str::uuid(),
        ]);

        $response->assertJsonValidationErrors(['header_logo']);

        $response2 = $this->postJson('/api/tenants', [
            'codigo' => 'acme',
            'nombre' => 'Acme',
            'dominio' => 'acme.com',
            'primary_color' => '#111111',
            'secondary_color' => '#222222',
            'danger_color' => '#333333',
            'success_color' => '#555555',
            'header_bg_color' => '#444444',
            'footer_bg_color' => '#444444',
            'header_logo' => 'data:application/pdf;base64,JVBERi0xLjQKJdcfqksKMSAwIG9iagogIDw8IC9UeXBlIC9DYXRhbG9nCiAgICAvUGFnZXMgMiAwIFI...',
            'footer_logo' => (string) Str::uuid(),
        ]);

        $response2->assertJsonValidationErrors(['header_logo']);
    }

    public function test_it_stores_uploaded_file_logos_in_tenants_directory(): void
    {
        Storage::fake('s3');

        $header = UploadedFile::fake()->image('header.png');
        $footer = UploadedFile::fake()->image('footer.svg', 100, 100);

        $response = $this->postJson('/api/tenants', [
            'codigo' => 'acme',
            'nombre' => 'Acme',
            'dominio' => 'acme.com',
            'primary_color' => '#111111',
            'secondary_color' => '#222222',
            'danger_color' => '#333333',
            'success_color' => '#555555',
            'header_bg_color' => '#444444',
            'footer_bg_color' => '#444444',
            'header_logo' => $header,
            'footer_logo' => $footer,
        ]);

        $response->assertCreated();

        $tenant = Tenant::query()->with(['headerLogo', 'footerLogo'])->where('codigo', 'acme')->firstOrFail();

        $this->assertNotNull($tenant->header_logo_id);
        $this->assertNotNull($tenant->footer_logo_id);

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

        $this->assertStringContainsString($tenant->headerLogo->key, $headerUrl);
        $this->assertStringContainsString($tenant->footerLogo->key, $footerUrl);
        $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->assertDatabaseHas('attachments', ['key' => $tenant->headerLogo->key]);
        $this->assertDatabaseHas('attachments', ['key' => $tenant->footerLogo->key]);
    }

    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));
    }

    public function test_it_stores_base64_logos_in_tenants_directory(): void
    {
        Storage::fake('s3');

        $base64Image = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==';

        $ftrUuid = (string) Str::uuid();
        $footerAttachment = Attachment::create([
            'key' => $ftrUuid,
            'path' => 'tenants/'.$ftrUuid.'.png',
            'filename' => 'logo_footer.png',
            'type' => AttachmentType::Image,
            'mime_type' => 'image/png',
        ]);

        $response = $this->postJson('/api/tenants', [
            'codigo' => 'acme',
            'nombre' => 'Acme',
            'dominio' => 'acme.com',
            'primary_color' => '#111111',
            'secondary_color' => '#222222',
            'danger_color' => '#333333',
            'success_color' => '#555555',
            'header_bg_color' => '#444444',
            'footer_bg_color' => '#444444',
            'header_logo' => $base64Image,
            'footer_logo' => $ftrUuid,
            'site_title' => 'Acme Store',
            'favicon' => $base64Image,
        ]);

        $response->assertCreated();

        $tenant = Tenant::query()->with(['headerLogo', 'favicon'])->where('codigo', 'acme')->firstOrFail();

        $this->assertNotNull($tenant->header_logo_id);
        $this->assertNotNull($tenant->favicon_id);

        $headerUrl = $response->json('data.header_logo');
        $faviconUrl = $response->json('data.favicon');

        $response->assertJsonPath('data.site_title', 'Acme Store');
        $this->assertStringContainsString($tenant->headerLogo->key, $headerUrl);
        $this->assertStringContainsString($tenant->favicon->key, $faviconUrl);
        $this->assertTrue(
            str_contains($headerUrl, 'Expires=') || str_contains($headerUrl, 'expiration=') || str_contains($headerUrl, 'X-Amz-Expires=')
        );

        $this->assertDatabaseHas('attachments', ['key' => $tenant->headerLogo->key]);
        $this->assertDatabaseHas('attachments', ['key' => $tenant->favicon->key]);
    }
}
