<?php

declare(strict_types=1);

namespace PortalPeople\users\controllers\api;

use OpenApi\Annotations as OA;
use PortalPeople\users\Module as UsersModule;
use Yii;
use yii\rest\Controller;

/**
 * @OA\Tag(
 *   name="Users",
 *   description="User authentication and session management"
 * )
 */
class UserController extends Controller
{
    /**
     * @OA\Post(
     *   path="/v1/user/login",
     *   tags={"Users"},
     *   summary="Authenticate user and return access token",
     *   @OA\RequestBody(
     *     required=true,
     *     @OA\MediaType(
     *       mediaType="application/json",
     *       @OA\Schema(
     *         required={"username","password"},
     *         @OA\Property(property="username", type="string"),
     *         @OA\Property(property="password", type="string", format="password")
     *       )
     *     )
     *   ),
     *   @OA\Response(response=200, description="Login successful, returns access_token"),
     *   @OA\Response(response=422, description="Validation errors")
     * )
     */
    public function actionLogin(): array
    {
        /** @var UsersModule|null $module */
        $module = Yii::$app->getModule('ngauge-users');

        if ($module instanceof UsersModule) {
            return $module->getAuthService()->login(Yii::$app->request->getBodyParams());
        }

        Yii::$app->response->statusCode = 503;
        return ['error' => 'Users module unavailable'];
    }
}
