<?php

namespace Tests\Feature\Attachable;

use App\Domains\Attachable\Enums\AttachmentType;
use App\Domains\Attachable\Exceptions\AttachmentStorageException;
use App\Domains\Attachable\Models\Attachment;
use App\Domains\Attachable\Models\AttachmentCrop;
use App\Domains\Attachable\Services\AttachmentService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Mockery;
use Tests\TestCase;

class AttachmentTest extends TestCase
{
    use RefreshDatabase;

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

        $file = UploadedFile::fake()->image('logo.png');

        $attachment = app(AttachmentService::class)->store(
            $file,
            'attachments/acme',
        );

        $this->assertSame(AttachmentType::Image, $attachment->type);
        $this->assertTrue(Str::isUuid($attachment->key));
        $this->assertSame('logo.png', $attachment->filename);
        $this->assertSame('attachments/acme/'.$attachment->key.'.png', $attachment->path);
        Storage::disk('s3')->assertExists('attachments/acme/'.$attachment->key.'.png');
        $this->assertDatabaseHas('attachments', [
            'id' => $attachment->id,
            'key' => $attachment->key,
            'path' => 'attachments/acme/'.$attachment->key.'.png',
            'filename' => 'logo.png',
            'type' => AttachmentType::Image->value,
        ]);

        $freshAttachment = Attachment::query()->findOrFail($attachment->id);

        $this->assertSame(AttachmentType::Image, $freshAttachment->type);
    }

    public function test_it_does_not_persist_the_attachment_when_the_s3_upload_fails(): void
    {
        $disk = Mockery::mock();
        Storage::shouldReceive('disk')
            ->once()
            ->with('s3')
            ->andReturn($disk);
        $disk->shouldReceive('putFileAs')
            ->once()
            ->with('attachments/globex', Mockery::type(UploadedFile::class), Mockery::on(static fn (string $value): bool => Str::isUuid(pathinfo($value, PATHINFO_FILENAME))))
            ->andReturn(false);

        try {
            app(AttachmentService::class)->store(
                UploadedFile::fake()->create('manual.pdf', 10, 'application/pdf'),
                'attachments/globex',
            );

            $this->fail('Expected an AttachmentStorageException to be thrown.');
        } catch (AttachmentStorageException) {
            $this->assertDatabaseCount('attachments', 0);
        }
    }

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

        $original = app(AttachmentService::class)->storeCroppedImageVariants(
            UploadedFile::fake()->image('product.jpg', 200, 100),
            'attachments/acme',
            [
                'desktop' => [
                    'crop_horizontal' => ['start_percentage' => 25, 'end_percentage' => 75],
                    'crop_vertical' => ['start_percentage' => 10, 'end_percentage' => 85],
                ],
                'mobile' => [
                    'crop_horizontal' => ['start_percentage' => 20, 'end_percentage' => 80],
                    'crop_vertical' => ['start_percentage' => 0, 'end_percentage' => 100],
                ],
            ],
        );

        $desktopCrop = $original->cropVariants->firstWhere('variant', AttachmentCrop::DESKTOP);
        $mobileCrop = $original->cropVariants->firstWhere('variant', AttachmentCrop::MOBILE);
        $cropped = $desktopCrop->croppedAttachment;

        $this->assertNotNull($cropped);
        $this->assertEquals(
            ['start_percentage' => 25.0, 'end_percentage' => 75.0],
            $desktopCrop->crop_horizontal,
        );
        $this->assertEquals(
            ['start_percentage' => 10.0, 'end_percentage' => 85.0],
            $desktopCrop->crop_vertical,
        );
        $this->assertTrue($cropped->cropSource->attachment->is($original));
        $this->assertDatabaseCount('attachments', 3);
        $this->assertDatabaseCount('attachment_crops', 2);
        $this->assertDatabaseHas('attachment_crops', [
            'attachment_id' => $original->id,
            'variant' => AttachmentCrop::DESKTOP,
            'cropped_attachment_id' => $cropped->id,
        ]);
        Storage::disk('s3')->assertExists($original->path);
        Storage::disk('s3')->assertExists($cropped->path);
        Storage::disk('s3')->assertExists($mobileCrop->croppedAttachment->path);

        $croppedSize = getimagesizefromstring(Storage::disk('s3')->get($cropped->path));

        $this->assertIsArray($croppedSize);
        $this->assertSame(100, $croppedSize[0]);
        $this->assertSame(75, $croppedSize[1]);
    }

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

        try {
            app(AttachmentService::class)->storeCroppedImageVariants(
                UploadedFile::fake()->image('product.png'),
                'attachments/acme',
                [
                    'desktop' => [
                        'crop_horizontal' => ['start_percentage' => 75, 'end_percentage' => 25],
                        'crop_vertical' => ['start_percentage' => 0, 'end_percentage' => 100],
                    ],
                    'mobile' => [
                        'crop_horizontal' => ['start_percentage' => 0, 'end_percentage' => 100],
                        'crop_vertical' => ['start_percentage' => 0, 'end_percentage' => 100],
                    ],
                ],
            );

            $this->fail('Expected an AttachmentStorageException to be thrown.');
        } catch (AttachmentStorageException) {
            $this->assertDatabaseCount('attachments', 0);
            $this->assertSame([], Storage::disk('s3')->allFiles());
        }
    }

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

        try {
            app(AttachmentService::class)->storeCroppedImageVariants(
                UploadedFile::fake()->createWithContent('invalid.png', 'not-an-image'),
                'attachments/acme',
                $this->fullCropVariants(),
            );

            $this->fail('Expected an AttachmentStorageException to be thrown.');
        } catch (AttachmentStorageException) {
            $this->assertDatabaseCount('attachments', 0);
            $this->assertSame([], Storage::disk('s3')->allFiles());
        }
    }

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

        $original = app(AttachmentService::class)->storeCroppedImageVariants(
            UploadedFile::fake()->image('product.png'),
            'attachments/acme',
            $this->fullCropVariants(),
        );
        $cropped = $original->cropVariants->pluck('croppedAttachment');

        app(AttachmentService::class)->delete($original);

        $this->assertDatabaseCount('attachments', 0);
        Storage::disk('s3')->assertMissing($original->path);
        foreach ($cropped as $variant) {
            Storage::disk('s3')->assertMissing($variant->path);
        }
    }

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

        $original = app(AttachmentService::class)->storeCroppedImageVariants(
            UploadedFile::fake()->image('product.jpg', 200, 100),
            'attachments/acme',
            $this->fullCropVariants(),
        );
        $previousCrops = $original->cropVariants->pluck('croppedAttachment');

        $updated = app(AttachmentService::class)->updateImageCropVariants(
            $original,
            [
                'desktop' => [
                    'crop_horizontal' => ['start_percentage' => 25, 'end_percentage' => 75],
                    'crop_vertical' => ['start_percentage' => 10, 'end_percentage' => 85],
                ],
                'mobile' => [
                    'crop_horizontal' => ['start_percentage' => 30, 'end_percentage' => 70],
                    'crop_vertical' => ['start_percentage' => 0, 'end_percentage' => 100],
                ],
            ],
        );

        foreach ($previousCrops as $previousCrop) {
            $this->assertDatabaseMissing('attachments', ['id' => $previousCrop->id]);
            Storage::disk('s3')->assertMissing($previousCrop->path);
        }

        $desktop = $updated->cropVariants->firstWhere('variant', AttachmentCrop::DESKTOP);

        $croppedSize = getimagesizefromstring(
            Storage::disk('s3')->get($desktop->croppedAttachment->path)
        );

        $this->assertIsArray($croppedSize);
        $this->assertSame(100, $croppedSize[0]);
        $this->assertSame(75, $croppedSize[1]);
    }

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

        Storage::disk('s3')->put('attachments/initech/spec.pdf', 'spec');

        $attachment = Attachment::query()->create([
            'path' => 'attachments/initech/spec.pdf',
            'key' => (string) Str::uuid(),
            'filename' => 'spec.pdf',
            'type' => AttachmentType::Pdf,
            'mime_type' => 'application/pdf',
            'extension' => 'pdf',
            'size' => 512,
        ]);

        app(AttachmentService::class)->delete($attachment);

        Storage::disk('s3')->assertMissing('attachments/initech/spec.pdf');
        $this->assertDatabaseMissing('attachments', [
            'id' => $attachment->id,
        ]);
    }

    public function test_it_keeps_the_database_record_when_the_s3_delete_fails(): void
    {
        $attachment = Attachment::query()->create([
            'path' => 'attachments/umbrella/audio.mp3',
            'key' => (string) Str::uuid(),
            'filename' => 'audio.mp3',
            'type' => AttachmentType::Audio,
            'mime_type' => 'audio/mpeg',
            'extension' => 'mp3',
            'size' => 1024,
        ]);

        $disk = Mockery::mock();
        Storage::shouldReceive('disk')
            ->once()
            ->with('s3')
            ->andReturn($disk);
        $disk->shouldReceive('delete')
            ->once()
            ->with('attachments/umbrella/audio.mp3')
            ->andReturn(false);

        try {
            app(AttachmentService::class)->delete($attachment);

            $this->fail('Expected an AttachmentStorageException to be thrown.');
        } catch (AttachmentStorageException) {
            $this->assertDatabaseHas('attachments', [
                'id' => $attachment->id,
            ]);
        }
    }

    private function fullCropVariants(): array
    {
        $crop = [
            'crop_horizontal' => ['start_percentage' => 0, 'end_percentage' => 100],
            'crop_vertical' => ['start_percentage' => 0, 'end_percentage' => 100],
        ];

        return ['desktop' => $crop, 'mobile' => $crop];
    }
}
