<?php

namespace App\Http\Controllers\Frontend\Shop;

use App\Actions\Shop\PurchaseItemAction;
use App\Http\Controllers\Controller;
use App\Http\Requests\Frontend\Shop\PurchaseRequest;
use App\Models\PwShop;
use App\Models\PwShopLog;
use App\Services\Analytics\StatsService;
use App\Services\Api\ApiFactory;
use App\Services\ItemDataService;
use Illuminate\Support\Facades\Auth;
use Inertia\Inertia;
use Inertia\Response;

final class ShopController extends Controller
{
    public function __construct(
        private ItemDataService $itemDataService,
        private ApiFactory $apiFactory,
        private PurchaseItemAction $purchaseItem,
        private StatsService $statsService,
    ) {}

    /**
     * Display shop items for purchase.
     */
    public function index(): Response
    {
        $user = Auth::user();
        $api = $this->apiFactory->make($user->ID);

        $serverOnline = $this->isServerOnline();
        $characters = [];

        if ($serverOnline) {
            $rolesData = $api->getRoles($user->ID);
            $roles = $rolesData['roles'] ?? [];

            foreach ($roles as $role) {
                $roleBase = $api->getRoleBase($role['id']);
                $roleStatus = $api->getRoleStatus($role['id']);

                $characters[] = [
                    'id' => $role['id'],
                    'name' => $role['name'],
                    'cls' => ($roleBase ?? [])['cls'] ?? 0,
                    'level' => ($roleStatus ?? [])['level'] ?? $role['level'] ?? 0,
                ];
            }
        }

        $items = PwShop::active()
            ->orderBy('created_at', 'desc')
            ->get()
            ->map(function ($item) {
                $itemData = $this->itemDataService->getItemData($item->item_id);
                $item->item_name = $itemData['name'];
                $item->item_color = $itemData['color'];
                $item->description = $itemData['description'];

                return $item;
            });

        return Inertia::render('frontend/shop/index', [
            'items' => $items,
            'characters' => $characters,
            'serverOnline' => $serverOnline,
            'userGold' => $user->gold ?? 0,
        ]);
    }

    /**
     * Process purchase.
     */
    public function purchase(PurchaseRequest $request)
    {
        $user = Auth::user();
        $item = PwShop::findOrFail($request->getItemId());

        if (! $item->is_active) {
            return back()->withErrors(['item_id' => 'This item is no longer available.']);
        }

        $result = $this->purchaseItem->handle(
            user: $user,
            item: $item,
            characterId: $request->getCharacterId(),
            quantity: $request->getQuantity(),
        );

        if ($result['success']) {
            return redirect()->route('dashboard.shop.index')
                ->with('success', $result['message']);
        }

        return back()->withErrors(['item_id' => $result['message']]);
    }

    /**
     * Display purchase history.
     */
    public function history(): Response
    {
        $user = Auth::user();

        $logs = PwShopLog::where('user_id', $user->ID)
            ->with('shopItem')
            ->orderBy('created_at', 'desc')
            ->paginate(20);

        return Inertia::render('frontend/shop/history', [
            'logs' => $logs,
        ]);
    }

    private function isServerOnline(): bool
    {
        $onlineData = $this->statsService->getOnlineData();

        return (bool) ($onlineData['serverOnline'] ?? false);
    }
}
