<?php

declare(strict_types=1);

namespace App\Policies;

use App\Models\MediaItem;
use App\Models\User;

class MediaItemPolicy
{
    public function viewAny(User $user): bool
    {
        return true;
    }

    public function view(User $user, MediaItem $mediaItem): bool
    {
        if ($user->hasRole('admin')) {
            return true;
        }

        if ($mediaItem->status !== MediaItem::STATUS_APPROVED) {
            return $mediaItem->created_by === $user->id
                || $mediaItem->uploader_id === $user->id;
        }

        if (! $mediaItem->project) {
            return false;
        }

        $project = $mediaItem->project;

        return $project->user_id === $user->id
            || $project->created_by === $user->id
            || ($project->producer && $project->producer->user_id === $user->id);
    }
}
