<?php

namespace App\Http\Controllers;

use App\Http\Requests\UserRegisterRequest;
use App\Models\UserModel;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Modules\AnnoRoute\Attribute\GetRoute;
use Modules\AnnoRoute\Attribute\PostRoute;
use Modules\AnnoRoute\Attribute\RequestAttribute;
use Modules\Common\Trait\RequestJson;
use Modules\SystemTool\Models\SysCarouselModel;
use Modules\SystemTool\Models\SysGridNavModel;

#[RequestAttribute('/api', authGuard: 'users')]
class IndexController
{
    use RequestJson;
    // 权限验证白名单
    protected array $noPermission = ['index', 'login', 'register', 'mail'];

    /** 获取首页信息 */
    #[GetRoute('/index')]
    public function index(): JsonResponse
    {
        $web_setting = site_config('web');

        return $this->success(compact('web_setting'));
    }

    /** 用户登录 */
    #[PostRoute('/login')]
    public function login(Request $request): JsonResponse
    {
        $credentials = $request->validate([
            'username' => 'required|min:4|alphaDash',
            'password' => 'required|min:4|alphaDash',
        ]);
        if (Auth::guard('users')->attempt($credentials, true)) {
            $data = $request->user('users')
                ->createToken($credentials['username'])
                ->toArray();
            return $this->success($data, __('user.login_success'));
        }
        return $this->error(__('user.login_error'));
    }

    /** 用户注册 */
    #[PostRoute('/register')]
    public function register(UserRegisterRequest $request): JsonResponse
    {
        $data = $request->validated();
        $model = new UserModel;
        $model->username = $data['username'];
        $model->password = password_hash($data['password'], PASSWORD_DEFAULT);
        $model->email = $data['email'];
        if ($model->save()) {
            return $this->success();
        }

        return $this->error('创建用户失败');
    }

    /** 获取首页数据（公开接口）：轮播图 + 宫格导航 */
    #[GetRoute('/home', false)]
    public function home(): JsonResponse
    {
        $site_title = site_config('web.subtitle');
        $carousel = SysCarouselModel::query()
            ->where('status', 0)
            ->orderBy('sort', 'desc')
            ->orderBy('id', 'desc')
            ->get();
        $gridNav = SysGridNavModel::query()
            ->where('status', 0)
            ->orderBy('sort', 'desc')
            ->orderBy('id', 'desc')
            ->get();

        return $this->success(compact('carousel', 'gridNav', 'site_title'));
    }
}
