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.CreateConfigDto;
import com.lesingle.modules.sys.entity.SysConfig;
import com.lesingle.modules.sys.service.ISysConfigService;
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("/config")
@RequiredArgsConstructor
public class SysConfigController {

    private final ISysConfigService configService;

    @PostMapping
    @Operation(summary = "创建配置")
    public Result<SysConfig> create(@Valid @RequestBody CreateConfigDto dto) {
        Long tenantId = SecurityUtil.getCurrentTenantId();
        return Result.success(configService.createConfig(dto, tenantId));
    }

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

    @GetMapping("/key/{key}")
    @Operation(summary = "根据键查询配置")
    public Result<SysConfig> findByKey(@PathVariable String key) {
        Long tenantId = SecurityUtil.getCurrentTenantId();
        return Result.success(configService.findByKey(key, tenantId));
    }

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

    @PatchMapping("/{id}")
    @Operation(summary = "更新配置")
    public Result<SysConfig> update(@PathVariable Long id, @RequestBody CreateConfigDto dto) {
        Long tenantId = SecurityUtil.getCurrentTenantId();
        return Result.success(configService.updateConfig(id, dto, tenantId));
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除配置")
    public Result<Void> remove(@PathVariable Long id) {
        Long tenantId = SecurityUtil.getCurrentTenantId();
        configService.removeConfig(id, tenantId);
        return Result.success();
    }
}
