package com.emoon.extent.migration.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import com.emoon.common.core.domain.R;
import com.emoon.common.json.utils.JsonUtils;
import com.emoon.common.web.core.BaseController;
import com.emoon.extent.migration.dto.DatabaseConfig;
import com.emoon.extent.migration.dto.MigrationRequest;
import com.emoon.extent.migration.dto.MigrationResult;
import com.emoon.extent.migration.service.DatabaseMigrationService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 数据库迁移控制器
 *
 * @author destiny
 * @date 2025/11/20 17:38
 */
@Slf4j
@RestController
@RequestMapping("/migration")
@RequiredArgsConstructor
public class MigrationController extends BaseController {

    private final DatabaseMigrationService databaseMigrationService;

    /**
     * 执行数据库迁移
     *
     * @param request 迁移请求参数
     * @return 迁移结果
     */
    @SaIgnore
    @PostMapping("/migrate")
    public R<MigrationResult> migrateTables(
        @Validated @RequestBody MigrationRequest request) {
        try {
            log.info("migrationRequest: {}", JsonUtils.toJsonString(request));
            MigrationResult result = databaseMigrationService.migrateTables(request);
            if (result.getSuccess()) {
                return R.ok("数据库迁移成功", result);
            } else {
                return R.fail("数据库迁移失败: " + result.getMessage(), result);
            }
        } catch (Exception e) {
            return R.fail("数据库迁移异常: " + e.getMessage());
        }
    }

    /**
     * 验证数据库连接
     *
     * @param databaseConfig 数据库配置
     * @return 验证结果
     */
    @SaIgnore
    @PostMapping("/validate-connection")
    public R<Boolean> validateConnection(
        @Validated @RequestBody DatabaseConfig databaseConfig) {
        try {
            boolean isValid = databaseMigrationService.validateConnection(databaseConfig);
            if (isValid) {
                return R.ok("数据库连接正常", true);
            } else {
                return R.fail("数据库连接失败", false);
            }
        } catch (Exception e) {
            return R.fail("数据库连接验证异常: " + e.getMessage());
        }
    }

    /**
     * 获取数据库迁移状态
     *
     * @return 系统状态
     */
    @GetMapping("/status")
    public R<String> getStatus() {
        return R.ok("数据库迁移服务运行正常", "ACTIVE");
    }
}
