<?php

namespace Workbench\App\Policies;

use Illuminate\Auth\Access\HandlesAuthorization;
use Spatie\MediaLibrary\HasMedia;
use Workbench\App\Models\User;

class PostPolicy
{
    use HandlesAuthorization;

    public function listMedia(User $user, HasMedia $model): bool
    {
        if (is_bool($user->policies['listMedia'])) {
            return $user->policies['listMedia'] === true;
        }

        return data_get($user->policies, 'listMedia.id') === $model->id
            &&  data_get($user->policies, 'listMedia.collection') === $collection;
    }

    public function storeMedia(User $user, ?HasMedia $model, ?string $collection = null): bool
    {
        if (is_bool($user->policies['storeMedia'])) {
            return $user->policies['storeMedia'] === true;
        }

        if (is_null($model)) {
            return data_get($user->policies, 'storeMedia.collection') === $collection;
        }

        return data_get($user->policies, 'storeMedia.id') === $model->id
            &&  data_get($user->policies, 'storeMedia.collection') === $collection;
    }

    public function updateMedia(User $user, HasMedia $model, string $collection): bool
    {
        if (is_bool($user->policies['updateMedia'])) {
            return $user->policies['updateMedia'] === true;
        }

        return data_get($user->policies, 'updateMedia.id') === $model->id
            &&  data_get($user->policies, 'updateMedia.collection') === $collection;
    }

    public function destroyMedia(User $user, HasMedia $model, string $collection): bool
    {
        if (is_bool($user->policies['destroyMedia'])) {
            return $user->policies['destroyMedia'] === true;
        }

        return data_get($user->policies, 'destroyMedia.id') === $model->id
            &&  data_get($user->policies, 'destroyMedia.collection') === $collection;
    }
}
