<?php

namespace App\Http\Controllers\Game;

use App\Http\Controllers\Controller;
use App\Models\GameEnterLog;
use Illuminate\Http\Request;

class GameEnterLogController extends Controller
{
    /**
     * Record game enter duration from client.
     * Params: userID, game_id, time (duration in milliseconds).
     */
    public function record(Request $request)
    {
        try {
            $userId = $request->input('userID') ?: $request->input('user_id');
            $gameId = $request->input('game_id') ?: $request->input('gameId');
            $durationMs = $request->input('time');
            if ($durationMs === null || $durationMs === '') {
                $durationMs = $request->input('duration');
            }

            if (empty($userId) || empty($gameId)) {
                return apiReturnFail('userID and game_id are required');
            }

            if ($durationMs === null || $durationMs === '' || !is_numeric($durationMs)) {
                return apiReturnFail('time is required (enter game duration in milliseconds)');
            }

            $durationMs = (int) $durationMs;
            if ($durationMs < 0) {
                return apiReturnFail('time must be a non-negative number');
            }

            $result = GameEnterLog::addLog([
                'user_id' => $userId,
                'game_id' => $gameId,
                'duration_ms' => $durationMs,
                'log_date' => $request->input('log_date') ?: date('Y-m-d'),
            ]);

            if ($result) {
                return apiReturnSuc(['message' => 'Recorded successfully']);
            }

            return apiReturnFail('Failed to record');
        } catch (\Exception $e) {
            \Log::error('Game enter log record error: ' . $e->getMessage(), [
                'request' => $request->all(),
                'trace' => $e->getTraceAsString(),
            ]);
            return apiReturnFail('Error: ' . $e->getMessage());
        }
    }
}
