<?php

namespace App\Http\Controllers\Admin;

use App\Enums\GameStatus;
use App\Enums\GameType;
use App\Http\Controllers\Controller;
use App\Models\Game;
use App\Queries\GameCatalogQuery;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class GameController extends Controller
{
    public function __construct(
        private GameCatalogQuery $gameCatalog,
    ) {
        $this->authorizeResource(Game::class, 'game');
    }

    public function index(): View
    {
        $games = Game::query()
            ->withCount('playerGameProfiles')
            ->orderBy('sort_order')
            ->orderBy('name')
            ->paginate(20);

        return view('admin.games.index', compact('games'));
    }

    public function create(): View
    {
        return view('admin.games.create', [
            'game' => new Game([
                'status' => GameStatus::Active,
                'game_type' => GameType::Both,
                'sort_order' => 0,
                'supports_ranks' => true,
                'supports_roles' => true,
                'supports_characters' => false,
                'supports_regions' => true,
                'supports_servers' => false,
            ]),
        ]);
    }

    public function store(Request $request): RedirectResponse
    {
        $validated = $this->validateGame($request);
        $validated = $this->normalizeBooleans($request, $validated);

        Game::create($validated);
        $this->gameCatalog->flush();

        return redirect()
            ->route('admin.games.index')
            ->with('status', 'Game created.');
    }

    public function edit(Game $game): View
    {
        return view('admin.games.edit', compact('game'));
    }

    public function update(Request $request, Game $game): RedirectResponse
    {
        $validated = $this->validateGame($request, $game);
        $validated = $this->normalizeBooleans($request, $validated);

        $game->update($validated);
        $this->gameCatalog->flush();

        return redirect()
            ->route('admin.games.index')
            ->with('status', 'Game updated.');
    }

    public function destroy(Game $game): RedirectResponse
    {
        $game->delete();
        $this->gameCatalog->flush();

        return redirect()
            ->route('admin.games.index')
            ->with('status', 'Game deleted.');
    }

    private function validateGame(Request $request, ?Game $game = null): array
    {
        return $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'slug' => ['required', 'string', 'max:255', 'unique:games,slug,'.($game?->id ?? 'NULL')],
            'short_name' => ['nullable', 'string', 'max:50'],
            'publisher' => ['nullable', 'string', 'max:255'],
            'description' => ['nullable', 'string'],
            'logo_path' => ['nullable', 'string', 'max:255'],
            'cover_path' => ['nullable', 'string', 'max:255'],
            'game_type' => ['required', 'string', 'in:'.implode(',', array_column(GameType::cases(), 'value'))],
            'status' => ['required', 'string', 'in:'.implode(',', array_column(GameStatus::cases(), 'value'))],
            'sort_order' => ['nullable', 'integer', 'min:0'],
            'supports_ranks' => ['sometimes', 'boolean'],
            'supports_roles' => ['sometimes', 'boolean'],
            'supports_characters' => ['sometimes', 'boolean'],
            'supports_regions' => ['sometimes', 'boolean'],
            'supports_servers' => ['sometimes', 'boolean'],
        ]);
    }

    private function normalizeBooleans(Request $request, array $validated): array
    {
        foreach (['supports_ranks', 'supports_roles', 'supports_characters', 'supports_regions', 'supports_servers'] as $field) {
            $validated[$field] = $request->boolean($field);
        }

        return $validated;
    }
}
