<?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\SysCarouselFormRequest;
use Modules\SystemTool\Models\SysCarouselModel;

/**
 * 首页轮播图管理
 */
#[RequestAttribute('/system/carousel', 'system.carousel')]
class SysCarouselController extends BaseController
{
    protected array $searchField = [
        'status' => '=',
    ];

    protected array $quickSearchField = ['title'];

    /** 查询轮播图列表 */
    #[GetRoute(authorize: 'query')]
    public function query(Request $request): JsonResponse
    {
        $query = SysCarouselModel::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(SysCarouselFormRequest $request): JsonResponse
    {
        $validated = $request->validated();
        $model = SysCarouselModel::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, SysCarouselFormRequest $request): JsonResponse
    {
        $validated = $request->validated();
        $model = SysCarouselModel::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 = SysCarouselModel::find($id);
        if (empty($model)) {
            return $this->error('轮播图不存在');
        }
        $model->delete();
        return $this->success();
    }
}
