package com.lesingle.modules.sys.controller;

import com.lesingle.common.result.PageResult;
import com.lesingle.common.result.Result;
import com.lesingle.common.util.SecurityUtil;
import com.lesingle.modules.sys.dto.CreateDictDto;
import com.lesingle.modules.sys.entity.SysDict;
import com.lesingle.modules.sys.service.ISysDictService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

@Tag(name = "数据字典")
@RestController
@RequestMapping("/dict")
@RequiredArgsConstructor
public class SysDictController {

    private final ISysDictService dictService;

    @PostMapping
    @Operation(summary = "创建字典")
    public Result<SysDict> create(@Valid @RequestBody CreateDictDto dto) {
        Long tenantId = SecurityUtil.getCurrentTenantId();
        return Result.success(dictService.createDict(dto, tenantId));
    }

    @GetMapping
    @Operation(summary = "查询字典列表")
    public Result<PageResult<SysDict>> findAll(
            @RequestParam(defaultValue = "1") Long page,
            @RequestParam(defaultValue = "10") Long pageSize) {
        Long tenantId = SecurityUtil.getCurrentTenantId();
        return Result.success(dictService.findAll(page, pageSize, tenantId));
    }

    @GetMapping("/code/{code}")
    @Operation(summary = "根据编码查询字典")
    public Result<SysDict> findByCode(@PathVariable String code) {
        Long tenantId = SecurityUtil.getCurrentTenantId();
        return Result.success(dictService.findByCode(code, tenantId));
    }

    @GetMapping("/{id}")
    @Operation(summary = "查询字典详情")
    public Result<SysDict> findOne(@PathVariable Long id) {
        Long tenantId = SecurityUtil.getCurrentTenantId();
        return Result.success(dictService.findDetail(id, tenantId));
    }

    @PatchMapping("/{id}")
    @Operation(summary = "更新字典")
    public Result<SysDict> update(@PathVariable Long id, @RequestBody CreateDictDto dto) {
        Long tenantId = SecurityUtil.getCurrentTenantId();
        return Result.success(dictService.updateDict(id, dto, tenantId));
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除字典")
    public Result<Void> remove(@PathVariable Long id) {
        Long tenantId = SecurityUtil.getCurrentTenantId();
        dictService.removeDict(id, tenantId);
        return Result.success();
    }
}
