package com.tashow.cloud.infra.controller.admin.db;

import static com.tashow.cloud.common.pojo.CommonResult.success;

import com.tashow.cloud.common.pojo.CommonResult;
import com.tashow.cloud.common.util.object.BeanUtils;
import com.tashow.cloud.infra.controller.admin.db.vo.DataSourceConfigRespVO;
import com.tashow.cloud.infra.controller.admin.db.vo.DataSourceConfigSaveReqVO;
import com.tashow.cloud.infra.dal.dataobject.db.DataSourceConfigDO;
import com.tashow.cloud.infra.service.db.DataSourceConfigService;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import java.util.List;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/** 管理后台 - 数据源配置 */
@RestController
@RequestMapping("/infra/data-source-config")
@Validated
public class DataSourceConfigController {

  @Resource private DataSourceConfigService dataSourceConfigService;

  /** 创建数据源配置 */
  @PostMapping("/create")
  @PreAuthorize("@ss.hasPermission('infra:data-source-config:create')")
  public CommonResult<Long> createDataSourceConfig(
      @Valid @RequestBody DataSourceConfigSaveReqVO createReqVO) {
    return success(dataSourceConfigService.createDataSourceConfig(createReqVO));
  }

  /** 更新数据源配置 */
  @PutMapping("/update")
  @PreAuthorize("@ss.hasPermission('infra:data-source-config:update')")
  public CommonResult<Boolean> updateDataSourceConfig(
      @Valid @RequestBody DataSourceConfigSaveReqVO updateReqVO) {
    dataSourceConfigService.updateDataSourceConfig(updateReqVO);
    return success(true);
  }

  /** 删除数据源配置 */
  @DeleteMapping("/delete")
  @PreAuthorize("@ss.hasPermission('infra:data-source-config:delete')")
  public CommonResult<Boolean> deleteDataSourceConfig(@RequestParam("id") Long id) {
    dataSourceConfigService.deleteDataSourceConfig(id);
    return success(true);
  }

  /** 获得数据源配置 */
  @GetMapping("/get")
  @PreAuthorize("@ss.hasPermission('infra:data-source-config:query')")
  public CommonResult<DataSourceConfigRespVO> getDataSourceConfig(@RequestParam("id") Long id) {
    DataSourceConfigDO config = dataSourceConfigService.getDataSourceConfig(id);
    return success(BeanUtils.toBean(config, DataSourceConfigRespVO.class));
  }

  /** 获得数据源配置列表 */
  @GetMapping("/list")
  @PreAuthorize("@ss.hasPermission('infra:data-source-config:query')")
  public CommonResult<List<DataSourceConfigRespVO>> getDataSourceConfigList() {
    List<DataSourceConfigDO> list = dataSourceConfigService.getDataSourceConfigList();
    return success(BeanUtils.toBean(list, DataSourceConfigRespVO.class));
  }
}
