package com.lesingle.common.config;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

/**
 * 数据库启动时轻量修复：
 * 由于本项目部分环境可能没有跑过最新的 init.sql，
 * 导致 `t_biz_contest_work` 缺少 `deleted` 字段，从而 MyBatis-Plus 逻辑删除查询报 500。
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ContestWorkSchemaRepair implements ApplicationRunner {

    private final JdbcTemplate jdbcTemplate;

    @Override
    public void run(ApplicationArguments args) {
        try {
            Integer columnCnt = jdbcTemplate.queryForObject(
                    "SELECT COUNT(*) " +
                            "FROM information_schema.columns " +
                            "WHERE table_schema = DATABASE() " +
                            "AND table_name = 't_biz_contest_work' " +
                            "AND column_name = 'deleted'",
                    Integer.class
            );

            if (columnCnt == null || columnCnt == 0) {
                log.warn("检测到表 `t_biz_contest_work` 缺少字段 `deleted`，尝试补齐...");
                jdbcTemplate.execute(
                        "ALTER TABLE t_biz_contest_work " +
                                "ADD COLUMN deleted tinyint NOT NULL DEFAULT '0' " +
                                "COMMENT '逻辑删除：0-未删除，1-已删除'"
                );
                log.info("补齐字段 `t_biz_contest_work.deleted` 完成");
            }
        } catch (Exception e) {
            // 不阻断启动，给调用方避免 500 需要依赖数据库权限/执行成功
            log.warn("补齐 `t_biz_contest_work.deleted` 失败：{}", e.getMessage());
        }
    }
}

