<?php

namespace Tests\Feature\Tenant;

use App\Domains\Tenant\Models\Tenant;
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 = \App\Domains\Attachable\Models\Attachment::create([
            'key' => $hdrKey,
            'path' => 'tenants/' . $hdrKey . '.png',
            'filename' => 'logo_header.png',
            'type' => \App\Domains\Attachable\Enums\AttachmentType::Image,
            'mime_type' => 'image/png',
        ]);
        $footerAttachment = \App\Domains\Attachable\Models\Attachment::create([
            'key' => $ftrKey,
            'path' => 'tenants/' . $ftrKey . '.png',
            'filename' => 'logo_footer.png',
            'type' => \App\Domains\Attachable\Enums\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_not_found_when_the_domain_does_not_exist(): void
    {
        $response = $this->getJson('/api/tenants/bootstrap/missing.example');

        $response->assertNotFound();
    }

    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 = \App\Domains\Attachable\Models\Attachment::create([
            'key' => $hdrUuid,
            'path' => 'tenants/' . $hdrUuid . '.png',
            'filename' => 'hdr.png',
            'type' => \App\Domains\Attachable\Enums\AttachmentType::Image,
            'mime_type' => 'image/png',
        ]);
        $ftrAttachment = \App\Domains\Attachable\Models\Attachment::create([
            'key' => $ftrUuid,
            'path' => 'tenants/' . $ftrUuid . '.png',
            'filename' => 'ftr.png',
            'type' => \App\Domains\Attachable\Enums\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 = \App\Domains\Attachable\Models\Attachment::create([
            'key' => $hdrKey,
            'path' => 'tenants/' . $hdrKey . '.png',
            'filename' => 'logo_header.png',
            'type' => \App\Domains\Attachable\Enums\AttachmentType::Image,
            'mime_type' => 'image/png',
        ]);
        $footerAttachment = \App\Domains\Attachable\Models\Attachment::create([
            'key' => $ftrKey,
            'path' => 'tenants/' . $ftrKey . '.png',
            'filename' => 'logo_footer.png',
            'type' => \App\Domains\Attachable\Enums\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 = \App\Domains\Attachable\Models\Attachment::create([
            'key' => $ftrUuid,
            'path' => 'tenants/' . $ftrUuid . '.png',
            'filename' => 'logo_footer.png',
            'type' => \App\Domains\Attachable\Enums\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]);
    }
}
