<?php

namespace Kylin\GameData\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Kylin\Core\ApiResponse;
use Kylin\Core\Controllers\BaseController;
use Kylin\Game\Models\Game;
use Kylin\GameData\Services\GameDataService;
use Kylin\GameData\Services\GameDataSyncService;

class GameDataController extends BaseController
{
    public function __construct(
        private readonly GameDataService $dataService,
        private readonly GameDataSyncService $syncService,
    ) {}

    /**
     * 获取游戏数据
     */
    public function show(string $appId, Request $request): JsonResponse
    {
        $game = Game::where('app_id', $appId)->firstOrFail();
        $userId = $request->input('user_id', $request->user()?->id);

        $save = $this->dataService->getSave((int) $userId, $game->id);

        if ($save === null) {
            return ApiResponse::success(null, '暂无存档');
        }

        return ApiResponse::success($save);
    }

    /**
     * 同步游戏数据
     */
    public function sync(string $appId, Request $request): JsonResponse
    {
        $game = Game::where('app_id', $appId)->firstOrFail();

        $validated = $request->validate([
            'data' => 'required|array',
            'client_version' => 'required|integer|min:1',
        ]);

        $userId = $request->user()?->id ?? $request->input('user_id');

        $save = $this->syncService->syncFromClient(
            (int) $userId,
            $game->id,
            $validated['data'],
            (int) $validated['client_version'],
        );

        return ApiResponse::success($save, '数据同步成功');
    }

    /**
     * 存档历史
     */
    public function history(string $appId, Request $request): JsonResponse
    {
        $game = Game::where('app_id', $appId)->firstOrFail();

        $validated = $request->validate([
            'limit' => 'nullable|integer|min:1|max:100',
        ]);

        $userId = $request->user()?->id ?? $request->input('user_id');

        $histories = $this->dataService->getHistory(
            (int) $userId,
            $game->id,
            $validated['limit'] ?? 20,
        );

        return ApiResponse::success($histories);
    }

    /**
     * 删除存档
     */
    public function destroy(string $appId, Request $request): JsonResponse
    {
        $game = Game::where('app_id', $appId)->firstOrFail();

        $userId = $request->user()?->id ?? $request->input('user_id');

        $this->dataService->deleteSave((int) $userId, $game->id);

        return ApiResponse::success(null, '存档已删除');
    }
}
