<?php

/** @noinspection LaravelUnknownEloquentFactoryInspection */

namespace DefStudio\GameEngine\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Casts\AsArrayObject;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use DefStudio\GameEngine\Database\Factories\MapFactory;
use DefStudio\GameEngine\Database\Factories\RunFactory;
use function game_engine;

/**
 * @property int $id;
 * @property int $story_id;
 * @property int $user_id;
 * @property Carbon|null $completed_at;
 * @property array<string, mixed> $state
 * @property-read Story $story,
 * @property-read User $user,
 *
 * @method static MapFactory factory(array|callable|int|null $count = null, array|callable $state = [])
 */
class Run extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'story_id',
    ];

    protected $casts = [
        'state' => AsArrayObject::class,
        'completed_at' => 'timestamp',
    ];

    protected $attributes = [
        'state' => '{}',
    ];

    public function getTable()
    {
        return config('game-engine.runs.table', parent::getTable());
    }

    protected static function newFactory(): RunFactory
    {
        return RunFactory::new();
    }

    /**
     * @return BelongsTo<Story, Run>
     */
    public function story(): BelongsTo
    {
        return $this->belongsTo(game_engine()->storyClass());
    }

    public function scopeOfStory(Builder $query, Story|int $story): void
    {
        $story_id = $story instanceof Story ? $story->id : $story;

        $query->where('story_id', $story_id);
    }

    public function scopeForUser(Builder $query, User|int $user): void
    {
        $user_id = $user instanceof User ? $user->id : $user;

        $query->where('user_id', $user_id);
    }

    public function scopeCompleted(Builder $query): void
    {
        $query->whereNotNull('completed_at');
    }

    public function scopeOngoing(Builder $query): void
    {
        $query->whereNull('completed_at');
    }

    /**
     * @return BelongsTo<User, Run>
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(game_engine()->userClass());
    }

    public function set_state(string $key, mixed $value): void
    {
        data_set($this->state, $key, $value);
    }

    public function get_state(string $key, mixed $default = null): mixed
    {
        return data_get($this->state, $key, $default);
    }
}
