<?php
declare(strict_types=1);

namespace App\Modules\PlayerAuth\Controllers\Api;

use App\Core\ApiController;
use App\Core\App;
use App\Core\Request;
use App\Core\Response;
use App\Core\Exceptions\ValidationException;
use App\Modules\PlayerAuth\Services\PlayerAuthService;

final class PlayerTokenController extends ApiController
{
    private PlayerAuthService $authService;

    public function __construct(Request $request)
    {
        parent::__construct();
        $this->request = $request;
        $this->authService = new PlayerAuthService();
    }

    public function login(Request $request): Response
    {
        try {
            $data = $this->validatedJson([
                'phone' => 'required|string',
                'password' => 'required|string',
                'device_info' => 'nullable|string|max:255',
            ]);
        } catch (ValidationException $e) {
            return $this->errorResponse('بيانات غير صالحة', 422, $e->errors());
        }

        $player = $this->authService->findPlayerByPhone($data['phone']);
        if (!$player || !$this->authService->verifyPassword($player, $data['password'])) {
            return $this->errorResponse('رقم الهاتف أو كلمة المرور غير صحيحة', 401);
        }

        $tokenData = $this->authService->createToken(
            (int) $player['id'],
            'mobile',
            $data['device_info'] ?? null
        );

        return $this->successResponse([
            'token' => $tokenData['token'],
            'expires_at' => $tokenData['expires_at'],
            'player' => [
                'id' => (int) $player['id'],
                'name' => $player['name_ar'],
                'phone' => $player['phone'],
            ],
        ], 201);
    }

    public function otpRequest(Request $request): Response
    {
        try {
            $data = $this->validatedJson([
                'phone' => 'required|string',
            ]);
        } catch (ValidationException $e) {
            return $this->errorResponse('بيانات غير صالحة', 422, $e->errors());
        }

        $player = $this->authService->findPlayerByPhone($data['phone']);
        if (!$player) {
            return $this->successResponse(['sent' => true]);
        }

        $otp = $this->authService->generateOtp((int) $player['id']);

        // TODO: Send OTP via SMS using SmsService
        // For now just return success (in production, integrate with SmsNotificationService)

        return $this->successResponse(['sent' => true]);
    }

    public function otpVerify(Request $request): Response
    {
        try {
            $data = $this->validatedJson([
                'phone' => 'required|string',
                'otp' => 'required|string|max:6',
                'device_info' => 'nullable|string|max:255',
            ]);
        } catch (ValidationException $e) {
            return $this->errorResponse('بيانات غير صالحة', 422, $e->errors());
        }

        $player = $this->authService->findPlayerByPhone($data['phone']);
        if (!$player) {
            return $this->errorResponse('رمز التحقق غير صحيح', 401);
        }

        if (!$this->authService->verifyOtp($player, $data['otp'])) {
            return $this->errorResponse('رمز التحقق غير صحيح أو منتهي الصلاحية', 401);
        }

        $tokenData = $this->authService->createToken(
            (int) $player['id'],
            'mobile',
            $data['device_info'] ?? null
        );

        return $this->successResponse([
            'token' => $tokenData['token'],
            'expires_at' => $tokenData['expires_at'],
            'player' => [
                'id' => (int) $player['id'],
                'name' => $player['name_ar'],
                'phone' => $player['phone'],
            ],
        ], 201);
    }

    public function refresh(Request $request): Response
    {
        $player = App::getInstance()->currentPlayer();
        $currentToken = $request->bearerToken();

        $tokenData = $this->authService->refreshToken($currentToken, (int) $player->id);

        return $this->successResponse([
            'token' => $tokenData['token'],
            'expires_at' => $tokenData['expires_at'],
        ], 201);
    }

    public function logout(Request $request): Response
    {
        $currentToken = $request->bearerToken();
        $this->authService->revokeToken($currentToken);

        return $this->successResponse(['logged_out' => true]);
    }
}
