<?php

namespace app\api\controller;

use ba\Tree;
use support\think\Db;
use app\common\controller\Frontend;
use app\common\library\token\TokenExpirationException;
use Webman\Http\Request;

class Index extends Frontend
{
    protected array $noNeedLogin = ['index'];

    public function index(Request $request)
    {
        $response = $this->initializeFrontend($request);
        if ($response !== null) return $response;

        $menus = [];
        if ($this->auth->isLogin()) {
            $rules = [];
            $userMenus = $this->auth->getMenus();
            foreach ($userMenus as $item) {
                if ($item['type'] == 'menu_dir') {
                    $menus[] = $item;
                } elseif ($item['type'] != 'menu') {
                    $rules[] = $item;
                }
            }
            $rules = array_values($rules);
        } else {
            $requiredLogin = filter_var($request->get('requiredLogin', false), FILTER_VALIDATE_BOOLEAN);
            if ($requiredLogin) {
                try {
                    $token = get_auth_token(['ba', 'user', 'token'], $request);
                    $this->auth->init($token);
                } catch (TokenExpirationException) {
                    return $this->error(__('Token expiration'), [], 409);
                }
                return $this->error(__('Please login first'), [
                    'type' => $this->auth::NEED_LOGIN
                ], $this->auth::LOGIN_RESPONSE_CODE);
            }

            $rules = Db::name('user_rule')
                ->where('status', 1)
                ->where('no_login_valid', 1)
                ->where('type', 'in', ['route', 'nav', 'button'])
                ->order('weigh', 'desc')
                ->select()
                ->toArray();
            $rules = Tree::instance()->assembleChild($rules);
        }

        return $this->success('', [
            'site' => [
                'siteName' => get_sys_config('site_name'),
                'version' => get_sys_config('version'),
                'cdnUrl' => full_url(),
                'upload' => keys_to_camel_case(get_upload_config($request), ['max_size', 'save_name', 'allowed_suffixes', 'allowed_mime_types']),
                'recordNumber' => get_sys_config('record_number'),
                'cdnUrlParams' => config('buildadmin.cdn_url_params'),
            ],
            'openMemberCenter' => config('buildadmin.open_member_center'),
            'userInfo' => $this->auth->getUserInfo(),
            'rules' => $rules,
            'menus' => $menus,
        ]);
    }
}
