<?php

namespace Tests\Feature\Tenant;

use App\Domains\Attachable\Enums\AttachmentType;
use App\Domains\Attachable\Models\Attachment;
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',
        ]);

        $tenant = Tenant::create([
            '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,
        ]);

        $response = $this->getJson('/api/tenants/bootstrap/acme.com');

        $response
            ->assertOk()
            ->assertJsonPath('data.codigo', 'acme')
            ->assertJsonPath('data.dominio', 'acme.com')
            ->assertJsonPath('data.primary_color', '#ff0000')
            ->assertJsonPath('data.secondary_color', '#00ff00')
            ->assertJsonPath('data.danger_color', '#0000ff')
            ->assertJsonPath('data.success_color', '#00ff00')
            ->assertJsonPath('data.header_bg_color', '#ffffff')->assertJsonPath('data.footer_bg_color', '#ffffff');

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

        $this->assertStringContainsString($headerAttachment->key, $headerUrl);
        $this->assertStringContainsString($footerAttachment->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->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/path?foo=bar#frag');

        $response = $this->getJson("/api/tenants/bootstrap/{$encodedDomain}");

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

    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/acme.com')
            ->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/acme.com')
            ->assertOk()
            ->assertJsonMissingPath('data.website_type')
            ->assertJsonPath('data.extras.contact.phone', '+54 341 555 0101')
            ->assertJsonMissingPath('data.extras.banner');
    }

    public function test_it_returns_not_found_when_the_domain_does_not_exist(): void
    {
        $response = $this->getJson('/api/tenants/bootstrap/missing.example');

        $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/acme.com');

        $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.faq')
            ->assertJsonPath('data.menues.0.submenues.0.label', 'Preguntas frecuentes')
            ->assertJsonPath('data.menues.0.submenues.0.parent_menu_code', 'help')
            ->assertJsonPath('data.menues.0.submenues.1.code', 'help.shipping');

        $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'][0]['static_content']);
        $assertCleanMenu($menus[0]);
        $this->assertArrayNotHasKey('static_content', $menus[0]);
        $this->assertArrayNotHasKey('static_content', $menus[0]['submenues'][1]);
    }

    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/acme.com')
            ->assertOk()
            ->assertJsonPath('data.menues.0.code', 'account')
            ->assertJsonMissing(['code' => 'admin.catalog']);
    }

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

        $firstResponse = $this->postJson('/api/tenants', [
            'codigo' => 'acme',
            'nombre' => 'Acme',
            'dominio' => 'https://ACME.com/path',
            '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.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=')
        );

        $secondResponse = $this->postJson('/api/tenants', [
            'codigo' => 'globex',
            'nombre' => 'Globex',
            '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' => (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/admin',
            '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/storefront',
        ]);

        $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',
        ]);

        $response
            ->assertOk()
            ->assertJsonPath('data.codigo', 'acme')
            ->assertJsonPath('data.nombre', 'Acme')
            ->assertJsonPath('data.primary_color', '#000000');

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

    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,
        ]);

        $response->assertCreated();

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

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

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

        $this->assertStringContainsString($tenant->headerLogo->key, $headerUrl);
        $this->assertTrue(
            str_contains($headerUrl, 'Expires=') || str_contains($headerUrl, 'expiration=') || str_contains($headerUrl, 'X-Amz-Expires=')
        );

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