package tech.easyflow.chatlog.repository.mysql;

import com.mybatisflex.core.row.Db;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import tech.easyflow.chatlog.support.ChatConstants;
import tech.easyflow.chatlog.support.ChatTableRouter;

import java.time.YearMonth;
import java.util.ArrayList;
import java.util.List;

@Repository
public class MySqlChatLogTableManager {

    private final JdbcTemplate jdbcTemplate;
    private final ChatTableRouter tableRouter;

    public MySqlChatLogTableManager(JdbcTemplate jdbcTemplate, ChatTableRouter tableRouter) {
        this.jdbcTemplate = jdbcTemplate;
        this.tableRouter = tableRouter;
    }

    public void ensureCurrentAndNextMonth() {
        ensureMonthTable(YearMonth.now());
        ensureMonthTable(YearMonth.now().plusMonths(1));
    }

    public void ensureMonthTable(YearMonth month) {
        String tableName = tableRouter.resolveLogTable(month);
        if (tableExists(tableName)) {
            return;
        }
        Db.selectObject("CREATE TABLE IF NOT EXISTS `" + tableName + "` LIKE `" + ChatConstants.CHAT_LOG_TEMPLATE + "`");
    }

    public List<YearMonth> listRecentExistingMonths(int retentionMonths) {
        List<YearMonth> months = new ArrayList<>();
        YearMonth current = YearMonth.now();
        for (int i = 0; i < retentionMonths; i++) {
            YearMonth month = current.minusMonths(i);
            if (tableExists(tableRouter.resolveLogTable(month))) {
                months.add(month);
            }
        }
        return months;
    }

    public void dropMonthTable(YearMonth month) {
        Db.selectObject("DROP TABLE IF EXISTS `" + tableRouter.resolveLogTable(month) + "`");
    }

    public boolean tableExists(String tableName) {
        Integer count = jdbcTemplate.queryForObject(
                "SELECT COUNT(1) FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = ?",
                Integer.class,
                tableName
        );
        return count != null && count > 0;
    }
}
