<?php

declare(strict_types=1);

namespace App\Policies;

use App\Models\Collection;
use App\Models\User;

class CollectionPolicy
{
    public function before($user, $ability)
    {
        if (! $user) {
            return null;
        }

        if ($this->isAdmin($user)) {
            return true;
        }

        return null;
    }

    public function view(?User $user, Collection $collection): bool
    {
        if ($user && $collection->isOwnedBy($user)) {
            return true;
        }

        return $collection->isPubliclyAccessible();
    }

    public function create(?User $user): bool
    {
        return (bool) $user;
    }

    public function update(User $user, Collection $collection): bool
    {
        return $collection->canBeManagedBy($user);
    }

    public function delete(User $user, Collection $collection): bool
    {
        if ((int) ($collection->group_id ?? 0) > 0) {
            return $collection->group?->canManageCollections($user) ?? false;
        }

        return $collection->isOwnedBy($user);
    }

    public function manageArtworks(User $user, Collection $collection): bool
    {
        return $collection->canManageArtworks($user);
    }

    public function manageMembers(User $user, Collection $collection): bool
    {
        return $collection->canManageMembers($user);
    }

    public function submit(User $user, Collection $collection): bool
    {
        return $collection->canReceiveSubmissionsFrom($user);
    }

    public function comment(User $user, Collection $collection): bool
    {
        return $collection->canReceiveCommentsFrom($user);
    }

    public function save(User $user, Collection $collection): bool
    {
        return $collection->canBeSavedBy($user);
    }

    private function isAdmin(User $user): bool
    {
        if (method_exists($user, 'isAdmin')) {
            return (bool) $user->isAdmin();
        }

        if (method_exists($user, 'hasRole')) {
            return (bool) $user->hasRole('admin');
        }

        return false;
    }
}
