<?php

/** @noinspection PhpUnhandledExceptionInspection */

namespace DefStudio\GameEngine\Http\Livewire\Teams;

use DefStudio\GameEngine\Models\Team;
use DefStudio\WiredTables\WiredTable;
use DefStudio\GameEngine\Models\Story;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\Relation;
use DefStudio\WiredTables\Configurations\TableConfiguration;

class StoriesTable extends WiredTable
{
    /** @var Team */
    public $team;

    protected function configure(TableConfiguration $configuration): void
    {
        $configuration
            ->pageSize(10)
            ->groupFilters(false);
    }

    protected function filters(): void
    {
        $this->filter(__('Display'), 'display')
            ->select(['subscribed' => __('Display Active')])
            ->placeholder(__('Display All Stories'))
            ->handle(fn(Builder|Relation $query) => $query->whereHas('teams', fn(Builder|Relation $subquery) => $subquery->where('teams.id', $this->team->id)));
    }

    protected function query(): Builder|Relation
    {
        return $this->team->organization
            ->stories()
            ->with('teams');
    }

    protected function columns(): void
    {
        $this->column(__('Title'), 'title')->searchable()->sortable();
        $this->column(__('Actions'))->view('game-engine::livewire.admin.teams.stories-table.actions', ['team' => $this->team]);
    }

    public function unsubscribe(int $story_id): void
    {
        /** @var Story $story */
        $story = $this->team->organization->stories()->findOrFail($story_id);
        $this->team->unsubscribe_from_story($story);
    }

    public function subscribe(int $story_id): void
    {
        /** @var Story $story */
        $story = $this->team->organization->stories()->findOrFail($story_id);
        $this->team->subscribe_to_story($story);
    }
}
