<?php

namespace DefStudio\GameEngine\Policies;

use DefStudio\GameEngine\Models\User;
use DefStudio\GameEngine\Models\Award;
use DefStudio\GameEngine\Enums\Feature;
use DefStudio\GameEngine\Enums\Permission;
use Illuminate\Auth\Access\HandlesAuthorization;

class AwardPolicy
{
    use HandlesAuthorization;

    public function view(User $user, Award $award): bool
    {
        if ($award->scope === null) {
            return true;
        }

        return $user->can('view', $award->scope);
    }

    public function save(User $user, Award $award): bool
    {
        if ($award->exists) {
            return $this->update($user, $award);
        }

        return $this->create($user, $award);
    }

    public function create(User $user, Award $award): bool
    {
        if ($award->scope === null) {
            return false;
        }

        if (Feature::scoped_awards->disabled()) {
            return false;
        }

        if (!$user->can(Permission::manage_awards->value)) {
            return false;
        }

        if ($award->parent !== null) {
            return $user->can('update', $award->parent);
        }

        return $user->can('update', $award->scope);
    }

    public function update(User $user, Award $award): bool
    {
        if ($award->scope === null) {
            return false;
        }

        if (Feature::scoped_awards->disabled()) {
            return false;
        }

        if (!$user->can(Permission::manage_awards->value)) {
            return false;
        }

        return $user->can('update', $award->scope);
    }

    public function delete(User $user, Award $award): bool
    {
        if ($award->scope === null) {
            return false;
        }

        if (Feature::scoped_awards->disabled()) {
            return false;
        }

        if (!$user->can(Permission::manage_awards->value)) {
            return false;
        }

        return $user->can('update', $award->scope);
    }
}
