package com.njcn.gather.systemops.database.util;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * 数据库运维文件名工具。
 */
public final class DatabaseFileNameUtil {

    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd");

    private DatabaseFileNameUtil() {
    }

    public static String appendTodayWithTask(String fileName, String taskNo) {
        String datedName = appendDate(fileName, LocalDate.now());
        int dotIndex = datedName.lastIndexOf('.');
        if (dotIndex > 0) {
            return datedName.substring(0, dotIndex) + "_" + taskNo + datedName.substring(dotIndex);
        }
        return datedName + "_" + taskNo;
    }

    private static String appendDate(String fileName, LocalDate date) {
        if (fileName == null || date == null) {
            return fileName;
        }
        String dateText = DATE_FORMATTER.format(date);
        int separatorIndex = Math.max(fileName.lastIndexOf('/'), fileName.lastIndexOf('\\'));
        int dotIndex = fileName.lastIndexOf('.');
        if (dotIndex > separatorIndex) {
            return fileName.substring(0, dotIndex) + "_" + dateText + fileName.substring(dotIndex);
        }
        return fileName + "_" + dateText;
    }
}
