<?php

namespace Zoomyboy\MedialibraryHelper\Tests\Feature;

use Illuminate\Support\Facades\Event;
use Workbench\App\Events\MediaChange;

test('it updates a single files properties', function () {
    Event::fake();
    $this->auth()->registerModel();
    $post = $this->newPost();
    $post->addMedia($this->pdfFile()->getPathname())->withCustomProperties(['test' => 'old'])->preservingOriginal()->toMediaCollection('multipleProperties');
    $media = $post->getFirstMedia('multipleProperties');

    $response = $this->patchJson("/mediaupload/{$media->id}", [
        'properties' => [
            'test' => 'new',
            'missing' => 'value',
        ],
    ]);

    $response->assertStatus(200);
    $this->assertEquals('new', $media->fresh()->getCustomProperty('test'));
    $this->assertEquals(null, $media->fresh()->getCustomProperty('missing'));
    $response->assertJsonPath('properties.test', 'new');
    $response->assertJsonMissingPath('properties.missing');
    Event::assertDispatched(MediaChange::class, fn ($event) => $event->model->is($post));
});

test('it validates a single files properties', function () {
    $this->auth()->registerModel();
    $post = $this->newPost();
    $post->addMedia($this->pdfFile()->getPathname())->withCustomProperties(['test' => 'old'])->preservingOriginal()->toMediaCollection('multipleProperties');
    $media = $post->getFirstMedia('multipleProperties');

    $response = $this->patchJson("/mediaupload/{$media->id}", [
        'properties' => [
            'test' => 'new  feswfewfwewefew wewe ew ewewf wefwfwefwefwefwewefewwedw sad fd',
        ],
    ]);

    $response->assertStatus(422);
    $response->assertJsonValidationErrors('properties.test');
});

test('it checks for authorization', function () {
    $this->auth(['updateMedia' => false])->registerModel();
    $post = $this->newPost();
    $post->addMedia($this->pdfFile()->getPathname())->preservingOriginal()->toMediaCollection('multipleProperties');
    $media = $post->getFirstMedia('multipleProperties');

    $response = $this->patchJson("/mediaupload/{$media->id}", [
        'properties' => [
            'test' => 'new',
            'missing' => 'value',
        ],
    ]);

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