<?php

namespace Zoomyboy\MedialibraryHelper\Tests\Feature;

use Carbon\Carbon;
use Illuminate\Support\Facades\Event;
use Zoomyboy\MedialibraryHelper\Tests\Events\MediaChange;
use Zoomyboy\MedialibraryHelper\Tests\Events\MediaStored;

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

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

    $response->assertStatus(201);
    $this->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.jpg');
    $response->assertJsonMissingPath('model_type');
    $response->assertJsonMissingPath('model_id');
});

test('it uploads heig image', function () {
    $this->auth()->registerModel();
    $post = $this->newPost();
    $content = base64_encode($this->getFile('heic.jpg', 'heic.jpg')->getContent());

    $this->postJson('/mediaupload', [
        'model' => 'post',
        'id' => $post->id,
        'collection' => 'conversionsWithDefault',
        'payload' => [
            'content' => $content,
            'name' => 'beispiel bild.jpg',
        ],
    ])->assertStatus(201);
});

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

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

    $response->assertStatus(201);
    $this->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'));
    $this->auth()->registerModel();
    $post = $this->newPost();
    $content = base64_encode($this->pdfFile()->getContent());

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

    $response->assertStatus(201);
    $this->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 () {
    $this->auth()->registerModel();
    $post = $this->newPost();
    $content = base64_encode($this->pdfFile()->getContent());

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

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

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

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

    $response = $this->postJson('/mediaupload', [
        'model' => 'post',
        'id' => $post->id,
        'collection' => 'multipleProperties',
        'payload' => [
            'content' => $content,
            'name' => 'beispiel bild.jpg',
        ],
    ]);

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

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

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

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

    $response->assertStatus(201);
    $this->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'));
    $this->auth()->registerModel()->withoutExceptionHandling();
    $post = $this->newPost();
    $content = base64_encode($this->pdfFile()->getContent());

    $response = $this->postJson('/mediaupload', [
        'model' => 'post',
        'id' => $post->id,
        'collection' => 'singleWithEvent',
        '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'));
    $this->auth()->registerModel()->withoutExceptionHandling();
    $post = $this->newPost();
    $content = base64_encode($this->pdfFile()->getContent());

    $response = $this->postJson('/mediaupload', [
        'model' => 'post',
        'id' => $post->id,
        'collection' => 'multipleFilesWithEvent',
        '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 () {
    $this->auth()->registerModel();
    $post = $this->newPost();
    $file = $this->pdfFile();
    $post->addMedia($file->getPathname())->preservingOriginal()->toMediaCollection('images');

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

    $response->assertStatus(201);
    $this->assertCount(3, $post->getMedia('images'));
    $media = $post->getMedia('images')->skip(1)->values();
    $this->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', 3028);
    $response->assertJsonPath('0.name', 'aaaa');
    $response->assertJsonPath('0.collection_name', 'images');
    $response->assertJsonPath('0.file_name', 'aaaa.jpg');
    $response->assertJsonMissingPath('0.model_type');
    $response->assertJsonMissingPath('0.model_id');
});

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

    $response = $this->postJson('/mediaupload', [
        'model' => 'post',
        'id' => $post->id,
        'collection' => 'defaultSingleFile',
        'payload' => [
            'content' => base64_encode($this->pdfFile()->getContent()),
            'name' => 'beispiel bild.jpg',
        ],
    ]);

    $response->assertStatus(403);
});

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

    $response = $this->postJson('/mediaupload', [
        'model' => 'post',
        'id' => $post->id,
        'collection' => 'defaultSingleFile',
        'payload' => [
            'content' => base64_encode($this->pdfFile()->getContent()),
            'name' => 'beispiel bild.jpg',
        ],
        ...$payload,
    ]);

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

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

    $response = $this->postJson('/mediaupload', [
        'model' => 'post',
        'id' => $post->id,
        'collection' => 'images',
        'payload' => [
            [
                'content' => base64_encode($this->pdfFile()->getContent()),
                'name' => 'beispiel bild.jpg',
            ],
        ],
        ...$payload,
    ]);

    $response->assertStatus(422);
    $response->assertJsonValidationErrors($invalidFieldName);
})->with(function () {
    yield [['model' => 'missingmodel'], 'model'];
    yield [['id' => -1], 'model'];
    yield [['collection' => 'missingcollection'], 'collection'];
    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'];
});
