<?php

namespace App\Modules\Auth\Http\Controllers;

use App\Core\Http\Controllers\BaseApiController;
use App\Http\Requests\Api\LoginRequest;
use App\Http\Requests\Api\RegisterRequest;
use App\Http\Resources\UserResource;
use App\Modules\Auth\Services\AuthService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

/**
 * مصادقة API (Sanctum) لتطبيق Flutter.
 */
class AuthController extends BaseApiController
{
    public function __construct(
        private readonly AuthService $auth,
    ) {}

    public function register(RegisterRequest $request): JsonResponse
    {
        $result = $this->auth->register($request->validated());

        return $this->successResponse('تم التسجيل بنجاح', [
            'user' => (new UserResource($result['user']))->resolve(),
            'token' => $result['token'],
        ], 201);
    }

    public function login(LoginRequest $request): JsonResponse
    {
        $data = $request->validated();

        $result = $this->auth->login($data['login'], $data['password']);

        return $this->successResponse('تم تسجيل الدخول بنجاح', [
            'user' => (new UserResource($result['user']))->resolve(),
            'token' => $result['token'],
        ]);
    }

    public function logout(Request $request): JsonResponse
    {
        $user = $request->user();
        if ($user !== null) {
            $this->auth->logout($user);
        }

        return $this->successResponse('تم تسجيل الخروج بنجاح', []);
    }
}
