<?php

namespace DefStudio\GameEngine\Policies;

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

class StoryPolicy
{
    use HandlesAuthorization;

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

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

    public function view(User $user, Story $target): bool
    {
        return $target->has_some_attached($user->current_teams);
    }

    public function play(User $user, Story $target): bool
    {
        return $target->has_some_attached($user->current_teams);
    }

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

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

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

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

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

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

        return $target->organization_id === $user->current_organization_id;
    }

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

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

        return $target->organization_id === $user->current_organization_id;
    }
}
