<?php

namespace DefStudio\GameEngine\Policies;

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

class TeamPolicy
{
    use HandlesAuthorization;

    public function viewAny(User $user): bool
    {
        if ($user->current_organization_id === null) {
            return false;
        }

        return $user->can(Permission::view_teams->value);
    }

    public function view(User $user, Team $target): bool
    {
        if ($user->current_organization_id === null) {
            return false;
        }

        if (!$user->is_current_organization($target->organization_id)) {
            return false;
        }

        return $user->has_attached($target);
    }

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

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

   public function create(User $user): bool
   {
       return $user->can(Permission::create_teams->value);
   }

    public function update(User $user, Team $target): bool
    {
        if (!$user->is_current_organization($target->organization_id)) {
            return false;
        }

        return $user->can(Permission::edit_teams->value);
    }

    public function delete(User $user, Team $target): bool
    {
        if (!$user->is_current_organization($target->organization_id)) {
            return false;
        }

        return $user->can(Permission::delete_teams->value);
    }
}
