<?php

namespace App\Http\Controllers;

use App\Models\News;
use App\Services\AzerothCoreAccountService;
use App\Services\NewsService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use Inertia\Inertia;
use Inertia\Response;
use Throwable;

class MainController extends Controller
{
    public function index(
        Request $request,
        AzerothCoreAccountService $accounts,
        NewsService $news,
    ): Response
    {
        $realmConfig = config('moonwell.realm');
        $rates = $realmConfig['rates'] ?? [];
        $user = Auth::user();
        $playersOnline = $accounts->onlinePlayerCount();

        try {
            $posts = $news->listForLanding()
                ->values()
                ->map(fn (News $item, int $index): array => [
                    'id' => $item->id,
                    'title' => $item->title,
                    'excerpt' => Str::limit(trim(strip_tags($item->body)), 200),
                    'date' => $item->created_at?->locale(app()->getLocale())->isoFormat('D MMMM YYYY'),
                    'tag' => 'Новости',
                    'tagType' => 'patch',
                    'image_url' => $item->image_url,
                    'featured' => $index === 0,
                ])
                ->all();
        } catch (Throwable $exception) {
            report($exception);

            $posts = [];
        }

        return Inertia::render('Landing/Main', [
            'realm' => [
                'name' => $realmConfig['realm_name'],
                'mode' => sprintf('PvE · %s rate · RU', $rates['experience'] ?? 'x1'),
                'realmlist' => $realmConfig['realmlist'],
                'online' => $playersOnline !== null,
                'players' => $playersOnline,
                'uptime' => '99.94%',
                'ping' => 38,
                'factions' => ['alliance' => 52, 'horde' => 48],
                'rates' => $rates,
                'client_version' => $realmConfig['client_version'] ?? '3.3.5a',
                'tagline' => $realmConfig['tagline'] ?? null,
                'server_name' => $realmConfig['server_name'] ?? 'MoonWell',
            ],
            'playUrl' => $user !== null ? route('cabinet.client') : '#join',
            'posts' => $posts,
            'tweaks' => [
                'variant' => 'forest',
                'particles' => true,
                'moon' => true,
            ],
            'registerEndpoint' => route('game-account.store'),
            'csrfToken' => csrf_token(),
            'auth' => [
                'authenticated' => $user !== null,
                'is_admin' => $user?->canAccessAdminPanel() ?? false,
                'username' => $user?->username,
                'login_url' => route('login'),
                'cabinet_url' => route('cabinet.index'),
                'admin_url' => route('admin.accounts.index'),
            ],
            'flash' => [
                'success' => $request->session()->get('registration_success'),
                'success_username' => $request->session()->get('registration_username'),
                'error' => $request->session()->get('registration_error'),
                'errors' => $this->errorBag(),
                'old' => $request->session()->getOldInput() ? [
                    'username' => $request->session()->getOldInput('username'),
                    'email' => $request->session()->getOldInput('email'),
                    'invite_code' => $request->session()->getOldInput('invite_code'),
                ] : [],
            ],
        ]);
    }

    /**
     * @return array<string, array<int, string>>
     */
    private function errorBag(): array
    {
        $errors = session()->get('errors');
        if (!$errors) {
            return [];
        }

        $bag = method_exists($errors, 'getBag') ? $errors->getBag('default') : $errors;

        return method_exists($bag, 'toArray') ? $bag->toArray() : [];
    }
}
