<?php

namespace DefStudio\GameEngine\Policies;

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

class OrganizationPolicy
{
    use HandlesAuthorization;

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

    public function view(User $user, Organization $target): bool
    {
        if (!$user->can(Permission::view_organizations->value)) {
            return false;
        }

        return $this->administrate($user, $target);
    }

    public function save(User $user, Organization $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_organizations->value);
    }

    public function update(User $user, Organization $target): bool
    {
        if (!$user->can(Permission::edit_organizations->value)) {
            return false;
        }

        return $this->administrate($user, $target);
    }

    public function delete(User $user, Organization $target): bool
    {
        if (!$user->can(Permission::delete_organizations->value)) {
            return false;
        }

        return $this->administrate($user, $target);
    }

    public function administrate(User $user, Organization $target): bool
    {
        $organization = $user->organizations->find($target->id);

        if (!$organization instanceof Organization) {
            return false;
        }

        return $organization->pivot->role === Role::admin->value;
    }

    public function switch(User $user, Organization $target): bool
    {
        return $user->belongs_to_organization($target);
    }
}
