<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\LoginRequest;
use App\Models\GameAccount;
use App\Services\AzerothCoreAccountService;
use Illuminate\Http\JsonResponse;
use OpenApi\Attributes as OA;

class LauncherAuthController extends Controller
{
    public function __construct(
        private readonly AzerothCoreAccountService $accounts,
    ) {
    }

    #[OA\Post(
        path: '/api/launcher/login',
        summary: 'Авторизация лаунчера',
        description: 'Авторизация по логину и паролю игрового аккаунта. Возвращает Bearer-токен для доступа к API.',
        tags: ['Launcher Auth'],
        requestBody: new OA\RequestBody(
            required: true,
            content: new OA\JsonContent(
                required: ['username', 'password'],
                properties: [
                    new OA\Property(property: 'username', type: 'string', minLength: 3, maxLength: 32, pattern: '^[A-Za-z0-9]+$', example: 'Player'),
                    new OA\Property(property: 'password', type: 'string', minLength: 3, maxLength: 32, example: 'secret123'),
                ],
            ),
        ),
        responses: [
            new OA\Response(
                response: 200,
                description: 'Успешная авторизация',
                content: new OA\JsonContent(
                    properties: [
                        new OA\Property(property: 'access_token', type: 'string', description: 'JWT access token'),
                        new OA\Property(property: 'token_type', type: 'string', example: 'Bearer'),
                        new OA\Property(property: 'expires_at', type: 'string', format: 'date-time', example: '2026-04-20T13:00:00+00:00'),
                    ],
                ),
            ),
            new OA\Response(
                response: 401,
                description: 'Неверный логин или пароль',
                content: new OA\JsonContent(
                    properties: [
                        new OA\Property(property: 'message', type: 'string', example: 'Неверный логин или пароль.'),
                    ],
                ),
            ),
            new OA\Response(
                response: 422,
                description: 'Ошибка валидации',
                content: new OA\JsonContent(
                    properties: [
                        new OA\Property(property: 'message', type: 'string'),
                        new OA\Property(property: 'errors', type: 'object'),
                    ],
                ),
            ),
            new OA\Response(response: 429, description: 'Слишком много запросов'),
        ],
    )]
    public function login(LoginRequest $request): JsonResponse
    {
        $user = $this->accounts->findUserByUsername($request->input('username'));

        if (! $user || ! $this->accounts->validatePassword($user, $request->input('password'))) {
            return response()->json([
                'message' => 'Неверный логин или пароль.',
            ], 401);
        }

        $gameAccount = GameAccount::on('azerothcore_auth')->findOrFail($user->id);
        $token = $gameAccount->createToken('launcher');

        return response()->json([
            'access_token' => $token->accessToken,
            'token_type' => 'Bearer',
            'expires_at' => $token->token->expires_at?->toIso8601String(),
        ]);
    }
}
