<?php

/** @noinspection PhpUnhandledExceptionInspection */

namespace DefStudio\GameEngine\Http\Livewire\Stories;

use DefStudio\GameEngine\Enums\Role;
use DefStudio\WiredTables\WiredTable;
use DefStudio\GameEngine\Models\Story;
use Illuminate\Database\Eloquent\Builder;
use Symfony\Component\HttpFoundation\Response;
use Illuminate\Database\Eloquent\Relations\Relation;
use DefStudio\GameEngine\Actions\Stories\DeleteStory;

class Table extends WiredTable
{
    protected function query(): Builder|Relation
    {
        /** @noinspection PhpVoidFunctionResultUsedInspection */
        $query = match (true) {
            \game_engine()->role(Role::super_admin) => \game_engine()->storyQuery(),
            \game_engine()->role(Role::admin) && \game_engine()->user()->current_organization_id => \game_engine()->user()->current_organization->stories(),
            default => abort(Response::HTTP_FORBIDDEN),
        };

        return $query
            ->withCount('maps')
            ->with('organization');
    }

    protected function columns(): void
    {
        $this->column(__('Title'), 'title')->searchable()->sortable();
        $this->column(__('Description'), 'description')->wrapText(true);
        $this->column(__('Maps'), 'maps_count');
        $this->column(__('Actions'))->view('game-engine::livewire.admin.stories.table.actions');
    }

    public function delete(Story $story): void
    {
        DeleteStory::run($story);
    }
}
