<?php

/**
 * Created by HanumanIT Co.,Ltd.
 * User: kongoon
 * Date: 8/11/2018 AD
 * Time: 12:49
 */

namespace api\modules\v1\controllers;

use api\components\Controller;
use yii\filters\AccessControl;
use api\models\forms\LoginForm;
use Yii;
use OpenApi\Annotations as OA;

/**
 * @OA\Tag(
 *   name="Guest",
 *   description="Public endpoints (about, login)"
 * )
 */
class GuestController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::class,
                'rules' => [
                    [
                        'actions' => ['index', 'login'],
                        'allow' => true,
                    ],
                ],
            ]
        ];
    }

    /**
     * @OA\Get(
     *   path="/guest",
     *   summary="About application",
     *   operationId="guestAbout",
     *   tags={"Guest"},
     *   @OA\Response(
     *     response=200,
     *     description="OK",
     *     @OA\JsonContent(ref="#/components/schemas/AboutApp")
     *   )
     * )
     */
    public function actionIndex()
    {
        $params = Yii::$app->params;
        return [
            'name' => $params['name'],
            'description' => $params['description'],
            'version' => $params['version'],
            'baseUrl' => $this->baseUrl()
        ];
    }


    /**
     * @OA\Post(
     *   path="/guest/login",
     *   summary="Login and get token",
     *   operationId="guestLogin",
     *   tags={"Guest"},
     *   requestBody={"$ref":"#/components/requestBodies/GuestLoginBody"},
     *   @OA\Response(response=200, ref="#/components/responses/GuestLoginOK"),
     *   @OA\Response(response=422, ref="#/components/responses/ValidationError"),
     *   @OA\Response(response=401, ref="#/components/responses/UnauthorizedResp")
     * )
     */
    public function actionLogin()
    {
        $dataRequest['LoginForm'] = Yii::$app->request->post();
        $model = new LoginForm();
        if ($model->load($dataRequest) && ($result = $model->login())) {
            return $this->apiItem($result);
        }
        return $this->apiValidate($model->errors);
    }
}