package com.qiaoba.module.tenant.controller;

import com.qiaoba.api.tenant.entity.SysTenantDatasource;
import com.qiaoba.common.base.result.AjaxResult;
import com.qiaoba.common.base.validate.AddGroup;
import com.qiaoba.common.base.validate.EditGroup;
import com.qiaoba.module.tenant.service.SysTenantDatasourceService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 租户数据源管理 Web层
 *
 * @author ailanyin
 * @version 1.0
 * @since 2023/5/30 10:52
 */
@RestController
@RequestMapping("/tenant/datasource")
@RequiredArgsConstructor
@Tag(name = "租户数据源管理")
public class SysTenantDatasourceController {

    private final SysTenantDatasourceService sysTenantDatasourceService;

    @PreAuthorize("hasAuthority('tenant:datasource:add')")
    @PostMapping
    @Operation(summary = "新增数据源")
    public AjaxResult add(@Validated(AddGroup.class) @RequestBody SysTenantDatasource sysTenantDatasource) {
        return AjaxResult.toAjax(sysTenantDatasourceService.insert(sysTenantDatasource));
    }

    @PreAuthorize("hasAuthority('tenant:datasource:edit')")
    @PutMapping
    @Operation(summary = "修改数据源")
    public AjaxResult edit(@Validated(EditGroup.class) @RequestBody SysTenantDatasource sysTenantDatasource) {
        return AjaxResult.toAjax(sysTenantDatasourceService.updateById(sysTenantDatasource));
    }

    @DeleteMapping("/{ids}")
    @PreAuthorize("hasAuthority('tenant:datasource:remove')")
    @Operation(summary = "删除数据源")
    public AjaxResult remove(@PathVariable List<String> ids) {
        return AjaxResult.toAjax(sysTenantDatasourceService.deleteByIds(ids));
    }

    @PreAuthorize("hasAuthority('tenant:datasource:list')")
    @GetMapping("/list")
    @Operation(summary = "获取列表")
    public AjaxResult list(@RequestParam String tenantId) {
        return AjaxResult.success(sysTenantDatasourceService.selectList(tenantId));
    }

    @PreAuthorize("hasAuthority('tenant:datasource:edit')")
    @PutMapping("/switchPrimary/{tenantId}/{id}")
    @Operation(summary = "切换为主数据源")
    public AjaxResult switchPrimary(@PathVariable String tenantId, @PathVariable String id) {
        return AjaxResult.toAjax(sysTenantDatasourceService.switchPrimary(tenantId, id));
    }
}
