package me.qwq.doghouse.util;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public final class DateUtils {

    // 缓存 formatter，行为接近 fastjson2
    private static final Map<String, DateTimeFormatter> FORMATTER_CACHE =
            new ConcurrentHashMap<>();

    private DateUtils() {
    }

    /**
     * 格式化 LocalDateTime
     *
     * @param dateTime LocalDateTime
     * @param pattern  日期格式，如 yyyy-MM-dd HH:mm:ss
     * @return 格式化后的字符串
     */
    public static String format(LocalDateTime dateTime, String pattern) {
        if (dateTime == null) {
            return null;
        }
        if (pattern == null || pattern.isEmpty()) {
            throw new IllegalArgumentException("pattern must not be null or empty");
        }

        DateTimeFormatter formatter =
                FORMATTER_CACHE.computeIfAbsent(pattern, DateTimeFormatter::ofPattern);

        return dateTime.format(formatter);
    }
    
    /**
     * 将给定字符串转换成 LocalDate
     * @param value 如 "20260101"
     * @param pattern 日期格式，如 yyyyMMdd
     * @return
     */
    public static LocalDate parse(String value, String pattern) {
        if (value == null) {
            return null;
        }
        if (pattern == null || pattern.isEmpty()) {
            throw new IllegalArgumentException("pattern must not be null or empty");
        }
        DateTimeFormatter formatter =
                FORMATTER_CACHE.computeIfAbsent(pattern, DateTimeFormatter::ofPattern);
        
        LocalDate date = LocalDate.parse(value, formatter);
        return date;
    }
}
