<?php

namespace Zoomyboy\MedialibraryHelper\Tests\Feature;

use Carbon\Carbon;
use Illuminate\Support\Facades\Event;
use Spatie\MediaLibrary\MediaCollections\Models\Media;
use Symfony\Component\Mime\MimeTypes;
use Workbench\App\Events\MediaChange;
use Workbench\App\Events\MediaStored;

test('it uploads a single file to a single file collection', function () {
    test()->auth()->registerModel()->withoutExceptionHandling();
    $post = test()->newPost();
    $content = base64_encode(test()->pdfFile()->getContent());

    $response = test()->postJson('/mediaupload', [
        'parent' => ['model' => 'post', 'collection_name' => 'defaultSingleFile', 'id' => $post->id],
        'payload' => [
            'content' => $content,
            'name' => 'beispiel bild.pdf',
        ],
    ]);

    $response->assertStatus(201);
    test()->assertCount(1, $post->getMedia('defaultSingleFile'));
    $media = $post->getFirstMedia('defaultSingleFile');
    $response->assertJsonPath('id', $media->id);
    $response->assertJsonPath('original_url', $media->getFullUrl());
    $response->assertJsonPath('size', 3028);
    $response->assertJsonPath('name', 'beispiel bild');
    $response->assertJsonPath('collection_name', 'defaultSingleFile');
    $response->assertJsonPath('file_name', 'beispiel-bild.pdf');
    $response->assertJsonPath('is_deferred', false);
    $response->assertJsonMissingPath('model_type');
    $response->assertJsonMissingPath('model_id');
});

test('it changes format', function () {
    test()->auth()->registerModel();
    $post = test()->newPost();
    $content = base64_encode(test()->pngFile()->getContent());

    $response = test()->postJson('/mediaupload', [
        'parent' => ['model' => 'post', 'collection_name' => 'singleJpegFile', 'id' => $post->id],
        'payload' => [
            'content' => $content,
            'name' => 'beispiel bild.png',
        ],
    ]);

    $response->assertStatus(201)
        ->assertJsonPath('size', 490278)
        ->assertJsonPath('file_name', 'beispiel-bild.jpg')
        ->assertJsonPath('mime_type', 'image/jpeg');
    $this->assertEquals('image/jpeg', MimeTypes::getDefault()->guessMimeType($post->getFirstMedia('singleJpegFile')->getPath()));
});

test('it uploads a single image to a single file collection', function () {
    test()->auth()->registerModel()->withoutExceptionHandling();
    $post = test()->newPost();
    $content = base64_encode(test()->jpgFile()->getContent());

    $response = test()->postJson('/mediaupload', [
        'parent' => ['model' => 'post', 'collection_name' => 'defaultSingleFile', 'id' => $post->id],
        'payload' => [
            'content' => $content,
            'name' => 'beispiel bild.jpg',
        ],
    ]);

    $response->assertStatus(201);
    test()->assertCount(1, $post->getMedia('defaultSingleFile'));
});

test('it forces a filename for a single collection', function () {
    Carbon::setTestNow(Carbon::parse('2023-04-04 00:00:00'));
    test()->auth()->registerModel();
    $post = test()->newPost();
    $content = base64_encode(test()->jpgFile()->getContent());

    $response = test()->postJson('/mediaupload', [
        'parent' => ['model' => 'post', 'collection_name' => 'singleForced', 'id' => $post->id],
        'payload' => [
            'content' => $content,
            'name' => 'beispiel bild.jpg',
        ],
    ]);

    $response->assertStatus(201);
    test()->assertEquals('beispiel-bild-2023-04-04.jpg', $post->getFirstMedia('singleForced')->file_name);
    $response->assertJsonPath('name', 'beispiel bild 2023-04-04');
    $response->assertJsonPath('file_name', 'beispiel-bild-2023-04-04.jpg');
});

test('it sets custom title when storing', function () {
    test()->auth()->registerModel();
    $post = test()->newPost();
    $content = base64_encode(test()->pdfFile()->getContent());

    $response = test()->postJson('/mediaupload', [
        'parent' => ['model' => 'post', 'collection_name' => 'singleStoringHook', 'id' => $post->id],
        'payload' => [
            'content' => $content,
            'name' => 'beispiel bild.jpg',
        ],
    ]);

    $response->assertStatus(201);
    $media = $post->getFirstMedia('singleStoringHook');

    test()->assertEquals('AAA', $media->getCustomProperty('use'));
    test()->assertEquals('beispiel bild', $media->getCustomProperty('ttt'));
});

test('it sets custom properties from properties method', function () {
    test()->auth()->registerModel();
    $post = test()->newPost();
    $content = base64_encode(test()->pdfFile()->getContent());

    $response = test()->postJson('/mediaupload', [
        'parent' => ['model' => 'post', 'collection_name' => 'multipleProperties', 'id' => $post->id],
        'payload' => [
            'content' => $content,
            'name' => 'beispiel bild.pdf',
        ],
    ]);

    $response->assertStatus(201);
    $media = $post->getFirstMedia('multipleProperties');

    test()->assertEquals('beispielBild.pdf', $media->getCustomProperty('test'));
});

test('it forces a filename for multiple collections', function () {
    Carbon::setTestNow(Carbon::parse('2023-04-04 00:00:00'));
    test()->auth()->registerModel();
    $post = test()->newPost();
    $content = base64_encode(test()->jpgFile()->getContent());

    $response = test()->postJson('/mediaupload', [
        'parent' => ['model' => 'post', 'collection_name' => 'multipleForced', 'id' => $post->id],
        'payload' => [
            [
                'content' => $content,
                'name' => 'beispiel bild.jpg',
            ],
        ],
    ]);

    $response->assertStatus(201);
    test()->assertEquals('beispiel-bild-2023-04-04.jpg', $post->getFirstMedia('multipleForced')->file_name);
});

test('it throws event when file has been uploaded', function () {
    Event::fake();
    Carbon::setTestNow(Carbon::parse('2023-04-04 00:00:00'));
    test()->auth()->registerModel()->withoutExceptionHandling();
    $post = test()->newPost();
    $content = base64_encode(test()->pdfFile()->getContent());

    $response = test()->postJson('/mediaupload', [
        'parent' => ['model' => 'post', 'collection_name' => 'singleWithEvent', 'id' => $post->id],
        'payload' => [
            'content' => $content,
            'name' => 'beispiel bild.jpg',
        ],
    ]);

    $response->assertStatus(201);
    Event::assertDispatched(MediaStored::class, fn ($event) => $event->media->id === $response->json('id'));
    Event::assertDispatched(MediaChange::class, fn ($event) => $event->model->is($post));
});

test('it throws event when multiple files uploaded', function () {
    Event::fake();
    Carbon::setTestNow(Carbon::parse('2023-04-04 00:00:00'));
    test()->auth()->registerModel()->withoutExceptionHandling();
    $post = test()->newPost();
    $content = base64_encode(test()->pdfFile()->getContent());

    $response = test()->postJson('/mediaupload', [
        'parent' => ['model' => 'post', 'collection_name' => 'multipleFilesWithEvent', 'id' => $post->id],
        'payload' => [
            [
                'content' => $content,
                'name' => 'beispiel bild.jpg',
            ],
            [
                'content' => $content,
                'name' => 'beispiel bild 1.jpg',
            ],
        ],
    ]);

    $response->assertStatus(201);
    Event::assertDispatched(MediaStored::class, fn ($event) => $event->media->id === $response->json('0.id'));
    Event::assertDispatched(MediaStored::class, fn ($event) => $event->media->id === $response->json('1.id'));
});

test('it uploads multiple files', function () {
    test()->auth()->registerModel();
    $post = test()->newPost();
    $file = test()->pdfFile();
    $post->addMedia($file->getPathname())->preservingOriginal()->toMediaCollection('images');

    $response = test()->postJson('/mediaupload', [
        'parent' => ['model' => 'post', 'collection_name' => 'images', 'id' => $post->id],
        'payload' => [
            [
                'content' => base64_encode($file->getContent()),
                'name' => 'aaaa.pdf',
            ],
            [
                'content' => base64_encode($file->getContent()),
                'name' => 'beispiel bild.pdf',
            ],
        ],
    ]);

    $response->assertStatus(201);
    test()->assertCount(3, $post->getMedia('images'));
    $this->assertEquals('application/pdf', MimeTypes::getDefault()->guessMimeType($post->getFirstMedia('images')->getPath()));
    $media = $post->getMedia('images')->skip(1)->values();
    test()->assertCount(2, $response->json());
    $response->assertJsonPath('0.id', $media->get(0)->id);
    $response->assertJsonPath('1.id', $media->get(1)->id);
    $response->assertJsonPath('0.original_url', $media->first()->getFullUrl());
    $response->assertJsonPath('0.size', 64576);
    $response->assertJsonPath('0.name', 'aaaa');
    $response->assertJsonPath('0.collection_name', 'images');
    $response->assertJsonPath('0.file_name', 'aaaa.pdf');
    $response->assertJsonMissingPath('0.model_type');
    $response->assertJsonMissingPath('0.model_id');
});

test('it returns 403 when not authorized', function () {
    test()->auth(['storeMedia' => false])->registerModel();
    $post = test()->newPost();

    test()->postJson('/mediaupload', [
        'parent' => ['model' => 'post', 'collection_name' => 'defaultSingleFile', 'id' => $post->id],
        'payload' => [
            'content' => base64_encode(test()->pdfFile()->getContent()),
            'name' => 'beispiel bild.jpg',
        ],
    ])->assertStatus(403);
});

test('it checks for model when running authorization', function () {
    $otherPost = test()->newPost();
    $post = test()->newPost();
    test()->auth(['storeMedia' => ['id' => $post->id, 'collection' => 'defaultSingleFile']])->registerModel();

    test()->postJson('/mediaupload', [
        'parent' => ['model' => 'post', 'collection_name' => 'defaultSingleFile', 'id' => $post->id],
        'payload' => [
            'content' => base64_encode(test()->pdfFile()->getContent()),
            'name' => 'beispiel bild.jpg',
        ],
    ])->assertStatus(201);

    test()->postJson('/mediaupload', [
        'parent' => ['model' => 'post', 'collection_name' => 'defaultSingleFile', 'id' => $otherPost->id],
        'payload' => [
            'content' => base64_encode(test()->pdfFile()->getContent()),
            'name' => 'beispiel bild.jpg',
        ],
    ])->assertStatus(403);
});

test('it checks for collection when running authorization', function () {
    $post = test()->newPost();
    test()->auth(['storeMedia' => ['id' => $post->id, 'collection' => 'defaultSingleFile']])->registerModel();

    test()->postJson('/mediaupload', [
        'parent' => ['model' => 'post', 'collection_name' => 'defaultSingleFile', 'id' => $post->id],
        'payload' => [
            'content' => base64_encode(test()->pdfFile()->getContent()),
            'name' => 'beispiel bild.jpg',
        ],
    ])->assertStatus(201);

    test()->postJson('/mediaupload', [
        'parent' => ['model' => 'post', 'collection_name' => 'singleWithEvent', 'id' => $post->id],
        'payload' => [
            'content' => base64_encode(test()->pdfFile()->getContent()),
            'name' => 'beispiel bild.jpg',
        ],
    ])->assertStatus(403);
});

test('it needs validation for single files', function (array $payloadOverwrites, string $invalidFieldName) {
    test()->auth()->registerModel();
    $post = test()->newPost();

    $payload = [
        'parent' => ['model' => 'post', 'collection_name' => 'defaultSingleFile', 'id' => $post->id],
        'payload' => [
            'content' => base64_encode(test()->pdfFile()->getContent()),
            'name' => 'beispiel bild.jpg',
        ],
    ];

    foreach ($payloadOverwrites as $key => $value) {
        data_set($payload, $key, $value);
    }

    $response = test()->postJson('/mediaupload', $payload);

    $response->assertStatus(422);
    $response->assertJsonValidationErrors($invalidFieldName);
})->with(function () {
    yield [['parent.model' => 'missingmodel'], 'parent.model'];
    yield [['parent.id' => -1], 'parent.id'];
    yield [['parent.collection_name' => 'missingcollection'], 'parent.collection_name'];
    yield [['payload.content' => []], 'payload.content'];
    yield [['payload.content' => ['UU']], 'payload.content'];
    yield [['payload.content' => null], 'payload.content'];
    yield [['payload.content' => ''], 'payload.content'];
    yield [['payload.content' => 1], 'payload.content'];
    yield [['payload.name' => ''], 'payload.name'];
    yield [['payload.name' => ['U']], 'payload.name'];
    yield [['payload.name' => 1], 'payload.name'];
    yield [['payload.name' => null], 'payload.name'];
    yield [['payload' => 'lalal'], 'payload'];
    yield [['payload' => 55], 'payload'];
});

test('it needs validation for multiple files', function (array $payloadOverwrites, string $invalidFieldName) {
    test()->auth()->registerModel();
    $post = test()->newPost();

    $payload = [
        'parent' => ['model' => 'post', 'collection_name' => 'images', 'id' => $post->id],
        'payload' => [
            [
                'content' => base64_encode(test()->pdfFile()->getContent()),
                'name' => 'beispiel bild.jpg',
            ],
        ],
    ];

    foreach ($payloadOverwrites as $key => $value) {
        data_set($payload, $key, $value);
    }

    $response = test()->postJson('/mediaupload', $payload);


    $response->assertStatus(422);
    $response->assertJsonValidationErrors($invalidFieldName);
})->with(function () {
    yield [['parent.model' => 'missingmodel'], 'parent.model'];
    yield [['parent.model' => 'post.missingcollection'], 'parent.model'];
    yield [['parent.id' => -1], 'parent.id'];
    yield [['payload' => 'lalal'], 'payload'];
    yield [['payload' => []], 'payload'];
    yield [['payload' => 1], 'payload'];
    yield [['payload' => [['name' => 'AAA', 'content' => []]]], 'payload.0.content'];
    yield [['payload' => [['name' => 'AAA', 'content' => ['UU']]]], 'payload.0.content'];
    yield [['payload' => [['name' => 'AAA', 'content' => null]]], 'payload.0.content'];
    yield [['payload' => [['name' => 'AAA', 'content' => '']]], 'payload.0.content'];
    yield [['payload' => [['name' => 'AAA', 'content' => 1]]], 'payload.0.content'];
    yield [['payload' => [['name' => '', 'content' => 'aaadfdf']]], 'payload.0.name'];
    yield [['payload' => [['name' => ['U'], 'content' => 'aaadfdf']]], 'payload.0.name'];
    yield [['payload' => [['name' => 1, 'content' => 'aaadfdf']]], 'payload.0.name'];
    yield [['payload' => [['name' => null, 'content' => 'aaadfdf']]], 'payload.0.name'];
    yield [['payload' => ['RRR']], 'payload.0'];
});
