package com.starry.admin.utils;

import cn.hutool.core.util.StrUtil;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

/**
 * Utilities for normalizing date/time range inputs.
 */
public final class DateRangeUtils {

    public static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    public static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    private DateRangeUtils() {}

    public static String normalizeStart(String raw) {
        if (StrUtil.isBlank(raw)) {
            return LocalDate.now().minusDays(6).format(DATE_FORMATTER) + " 00:00:00";
        }
        if (raw.length() > 10) {
            LocalDateTime.parse(raw, DATE_TIME_FORMATTER);
            return raw;
        }
        return raw + " 00:00:00";
    }

    public static String normalizeEnd(String raw) {
        if (StrUtil.isBlank(raw)) {
            return LocalDate.now().format(DATE_FORMATTER) + " 23:59:59";
        }
        if (raw.length() > 10) {
            LocalDateTime.parse(raw, DATE_TIME_FORMATTER);
            return raw;
        }
        return raw + " 23:59:59";
    }

    public static String normalizeStartOptional(String raw) {
        if (StrUtil.isBlank(raw)) {
            return null;
        }
        return normalizeFlexible(raw, false);
    }

    public static String normalizeEndOptional(String raw) {
        if (StrUtil.isBlank(raw)) {
            return null;
        }
        return normalizeFlexible(raw, true);
    }

    private static String normalizeFlexible(String raw, boolean isEnd) {
        String candidate = raw.trim().replace('T', ' ').replace("Z", "");
        if (candidate.length() <= 10) {
            candidate = candidate + (isEnd ? " 23:59:59" : " 00:00:00");
        } else if (candidate.length() > 19) {
            candidate = candidate.substring(0, 19);
        }
        try {
            LocalDateTime.parse(candidate, DATE_TIME_FORMATTER);
            return candidate;
        } catch (DateTimeParseException ex) {
            return candidate;
        }
    }
}
