package com.ga.common.util;

import java.time.LocalDate;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoUnit;

/**
 * 날짜/정산월 유틸. 정산월 포맷은 "yyyyMM" 6자리.
 */
public final class DateUtil {

    private DateUtil() {}

    public static final DateTimeFormatter FMT_DATE      = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    public static final DateTimeFormatter FMT_DATETIME  = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    public static final DateTimeFormatter FMT_MONTH     = DateTimeFormatter.ofPattern("yyyyMM");
    public static final DateTimeFormatter FMT_DATE_KOR  = DateTimeFormatter.ofPattern("yyyy년 MM월 dd일");

    public static String today() {
        return LocalDate.now().format(FMT_DATE);
    }

    public static String getSettleMonth() {
        return YearMonth.now().format(FMT_MONTH);
    }

    public static String getSettleMonth(LocalDate date) {
        return YearMonth.from(date).format(FMT_MONTH);
    }

    /** "202605" → ["2026-05-01", "2026-05-31"] */
    public static String[] getMonthRange(String settleMonth) {
        YearMonth ym = YearMonth.parse(settleMonth, FMT_MONTH);
        return new String[] {
                ym.atDay(1).format(FMT_DATE),
                ym.atEndOfMonth().format(FMT_DATE)
        };
    }

    public static int calcMonthDiff(String fromYyyymm, String toYyyymm) {
        YearMonth from = YearMonth.parse(fromYyyymm, FMT_MONTH);
        YearMonth to   = YearMonth.parse(toYyyymm,   FMT_MONTH);
        return (int) ChronoUnit.MONTHS.between(from, to);
    }

    public static int calcMonthDiff(LocalDate from, LocalDate to) {
        return (int) ChronoUnit.MONTHS.between(YearMonth.from(from), YearMonth.from(to));
    }

    public static LocalDate parseDate(String s, String pattern) {
        if (s == null || s.isBlank()) return null;
        try {
            return LocalDate.parse(s, DateTimeFormatter.ofPattern(pattern));
        } catch (DateTimeParseException e) {
            return null;
        }
    }

    public static String format(LocalDate date, String pattern) {
        return date == null ? null : date.format(DateTimeFormatter.ofPattern(pattern));
    }

    public static String addMonth(String yyyymm, int months) {
        return YearMonth.parse(yyyymm, FMT_MONTH).plusMonths(months).format(FMT_MONTH);
    }
}
