<?php

namespace app\api\controller;

use ba\Random;
use ba\Captcha;
use ba\ClickCaptcha;
use app\common\controller\Api;
use app\common\facade\Token;
use app\admin\library\Auth as AdminAuth;
use app\common\library\Auth as UserAuth;
use Webman\Http\Request;
use support\Response;

class Common extends Api
{
    public function captcha(Request $request): Response
    {
        $response = $this->initializeApi($request);
        if ($response !== null) return $response;

        $captchaId = $request->get('id', $request->post('id', ''));
        $config = [
            'codeSet' => '123456789',
            'fontSize' => 22,
            'useCurve' => false,
            'useNoise' => true,
            'length' => 4,
            'bg' => [255, 255, 255],
        ];
        $captcha = new Captcha($config);
        return $captcha->entry($captchaId);
    }

    public function clickCaptcha(Request $request): Response
    {
        $response = $this->initializeApi($request);
        if ($response !== null) return $response;

        $id = $request->get('id', $request->post('id', ''));
        $captcha = new ClickCaptcha();
        return $this->success('', $captcha->creat($id));
    }

    public function checkClickCaptcha(Request $request): Response
    {
        $response = $this->initializeApi($request);
        if ($response !== null) return $response;

        $id = $request->post('id', '');
        $info = $request->post('info', '');
        $unset = filter_var($request->post('unset', false), FILTER_VALIDATE_BOOLEAN);
        $captcha = new ClickCaptcha();
        if ($captcha->check($id, $info, $unset)) return $this->success();
        return $this->error();
    }

    public function refreshToken(Request $request): Response
    {
        $response = $this->initializeApi($request);
        if ($response !== null) return $response;

        $refreshToken = $request->post('refreshToken', '');
        $refreshToken = Token::get($refreshToken);

        if (!$refreshToken || $refreshToken['expire_time'] < time()) {
            return $this->error(__('Login expired, please login again.'));
        }

        $newToken = Random::uuid();

        if ($refreshToken['type'] == AdminAuth::TOKEN_TYPE . '-refresh') {
            Token::set($newToken, AdminAuth::TOKEN_TYPE, $refreshToken['user_id'], (int)config('buildadmin.admin_token_keep_time', 259200));
        }
        if ($refreshToken['type'] == UserAuth::TOKEN_TYPE . '-refresh') {
            Token::set($newToken, UserAuth::TOKEN_TYPE, $refreshToken['user_id'], (int)config('buildadmin.user_token_keep_time', 259200));
        }

        return $this->success('', [
            'type' => $refreshToken['type'],
            'token' => $newToken
        ]);
    }
}
