<?php

namespace App\Http\Controllers\Api\V1\Client\games;

use App\Http\Controllers\Controller;
use App\Http\Requests\Api\V1\Client\Games\CheckWordlingGameRequest;
use App\Http\Requests\Api\V1\Client\Games\GetActiveWordlingGamesRequest;
use App\Http\Requests\Api\V1\Client\Games\GetWordlingGameResultRequest;
use App\Http\Requests\Api\V1\Client\Games\GetWordlingGamesRequest;
use App\Http\Requests\Api\V1\Client\Games\GetWordlingSubmissionsRequest;
use App\Services\Games\WordlingGameService;

class WordlingGameController extends Controller
{
    use \App\Traits\Formatter;

    protected $wordlingGameService;

    public function __construct(WordlingGameService $wordlingGameService)
    {
        $this->wordlingGameService = $wordlingGameService;
    }

    /**
     * Handle word checking logic
     */
    public function checkWordlingGame(CheckWordlingGameRequest $request)
    {
        $validated = $request->validated();
        $user = auth('client')->user();

        $result = $this->wordlingGameService->checkWord($user, $validated);

        if (! $result['success']) {
            return $this->withError($result['message']);
        }

        return $this->withSuccess($result['data']);
    }

    /**
     * Get user's wordling submissions - Only for active games
     */
    public function getWordlingSubmissions(GetWordlingSubmissionsRequest $request)
    {
        $validated = $request->validated();
        $user = auth('client')->user();

        $data = $this->wordlingGameService->getSubmissions($user, $validated);

        return $this->withSuccess($data);
    }

    /**
     * Get game result with player stats and round state - Only for active games
     */
    public function getGameResult(GetWordlingGameResultRequest $request)
    {
        $validated = $request->validated();
        $user = auth('client')->user();

        $data = $this->wordlingGameService->getGameResult($user, $validated);

        return $this->withSuccess($data);
    }

    /**
     * Get all games by month, date, or game_id - Only active games
     */
    public function getWordlingGames(GetWordlingGamesRequest $request)
    {
        $validated = $request->validated();
        $user = auth('client')->user();

        $result = $this->wordlingGameService->getGamesList($user, $validated);

        if (! $result['success']) {
             return $this->withError($result['message']);
        }

        return $this->withSuccess($result['data']);
    }

    /**
     * Get only active games for the frontend
     */
    public function getActiveWordlingGames(GetActiveWordlingGamesRequest $request)
    {
        $validated = $request->validated();
        $user = auth('client')->user();

        $result = $this->wordlingGameService->getActiveGamesList($user, $validated);

        if (! $result['success']) {
             return $this->withError($result['message']);
        }

        return $this->withSuccess($result['data']);
    }
}
