<?php

namespace Modules\SystemTool\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Modules\AnnoRoute\Attribute\DeleteRoute;
use Modules\AnnoRoute\Attribute\GetRoute;
use Modules\AnnoRoute\Attribute\PostRoute;
use Modules\AnnoRoute\Attribute\PutRoute;
use Modules\AnnoRoute\Attribute\RequestAttribute;
use Modules\Common\Http\Controllers\BaseController;
use Modules\SystemTool\Http\Requests\SysGridNavFormRequest;
use Modules\SystemTool\Models\SysGridNavModel;

/**
 * 首页宫格导航管理
 */
#[RequestAttribute('/system/grid-nav', 'system.grid-nav')]
class SysGridNavController extends BaseController
{
    protected array $searchField = [
        'status' => '=',
    ];

    protected array $quickSearchField = ['title'];

    /** 查询宫格导航列表 */
    #[GetRoute(authorize: 'query')]
    public function query(Request $request): JsonResponse
    {
        $query = SysGridNavModel::query();
        $data = $this->buildSearch($request->all(), $query)
            ->orderBy('sort', 'desc')
            ->orderBy('id', 'desc')
            ->paginate($request->input('pageSize', 10))
            ->toArray();
        return $this->success($data);
    }

    /** 创建宫格导航 */
    #[PostRoute(authorize: 'create')]
    public function create(SysGridNavFormRequest $request): JsonResponse
    {
        $validated = $request->validated();
        $model = SysGridNavModel::create($validated);
        if (empty($model)) {
            return $this->error();
        }
        return $this->success();
    }

    /** 编辑宫格导航 */
    #[PutRoute(
        route: '/{id}',
        authorize: 'update',
        where: ['id' => '[0-9]+']
    )]
    public function update(int $id, SysGridNavFormRequest $request): JsonResponse
    {
        $validated = $request->validated();
        $model = SysGridNavModel::find($id);
        if (empty($model)) {
            return $this->error('宫格导航不存在');
        }
        $model->update($validated);
        return $this->success();
    }

    /** 删除宫格导航 */
    #[DeleteRoute(
        route: '/{id}',
        authorize: 'delete',
        where: ['id' => '[0-9]+']
    )]
    public function delete(int $id): JsonResponse
    {
        $model = SysGridNavModel::find($id);
        if (empty($model)) {
            return $this->error('宫格导航不存在');
        }
        $model->delete();
        return $this->success();
    }
}
