package com.yd.csf.service.audit;

import com.yd.csf.service.annotation.AuditField;
import lombok.RequiredArgsConstructor;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@RequiredArgsConstructor
public class FieldLabelResolver {

    private final JdbcTemplate jdbcTemplate;

    private final Map<String, String> cache = new ConcurrentHashMap<>();

    private static final String SQL = "SELECT COLUMN_COMMENT FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = ?";

    /**
     * 获取字段中文名，优先级：
     * 1. @AuditField.label
     * 2. information_schema.COLUMNS.COLUMN_COMMENT
     * 3. field 名本身
     */
    public String resolve(Field field, String tableName) {
        AuditField auditField = field.getAnnotation(AuditField.class);
        if (auditField != null && !auditField.label().isEmpty()) {
            return auditField.label();
        }

        String columnName = camelToUnderscore(field.getName());
        String cacheKey = tableName + "." + columnName;
        String comment = cache.computeIfAbsent(cacheKey, k -> {
            try {
                return jdbcTemplate.queryForObject(SQL, String.class, tableName, columnName);
            } catch (Exception e) {
                return null;
            }
        });

        if (comment != null && !comment.isEmpty()) {
            return comment;
        }

        return field.getName();
    }

    private String camelToUnderscore(String camel) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < camel.length(); i++) {
            char c = camel.charAt(i);
            if (Character.isUpperCase(c)) {
                sb.append('_').append(Character.toLowerCase(c));
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }
}
