<?php

/** @noinspection PhpPossiblePolymorphicInvocationInspection */

namespace DefStudio\GameEngine\Actions\Runs;

use DefStudio\Actions\Action;
use DefStudio\GameEngine\Models\Run;
use Illuminate\Support\Facades\Gate;
use DefStudio\GameEngine\Models\User;
use DefStudio\GameEngine\Models\Story;

/**
 * @method static Run run(Story $story, User $user)
 */
class GetActiveRun extends Action
{
    public function handle(Story $story, User $user): Run|null
    {
        return $this->active_run_if_exists($story, $user);
    }

    public function find_or_create(Story $story, User $user): Run
    {
        $run = $this->active_run_if_exists($story, $user);

        if ($run instanceof Run) {
            return $run;
        }

        Gate::forUser($user)->authorize('play', $story);

        /** @var Run $run */
        $run = game_engine()->runQuery()->create([
            'user_id' => $user->id,
            'story_id' => $story->id,
        ]);

        $run->setRelation('user', $user);
        $run->setRelation('story', $story);

        return $run;
    }

    private function active_run_if_exists(Story $story, User $user): Run|null
    {
        $run = game_engine()->runQuery()
            ->forUser($user)
            ->ofStory($story)
            ->ongoing()
            ->first();

        $run?->setRelation('user', $user);
        $run?->setRelation('story', $story);

        return $run;
    }
}
