package hr.com.port.ips.eracun.helper;

import hr.com.port.ips.eracun.boot.EracunSyncConfig;
import hr.com.port.ips.eracun.modeli.PosrednikType;
import hr.com.port.konstante.Configs;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.time.LocalDateTime;
import org.apache.log4j.Logger;


public class DokumentFileHelper {
	
	static Logger logger = Logger.getLogger(DokumentFileHelper.class);

    public static void saveXml(String xmlContent, String filePath) throws IOException {
        File file = new File(filePath);
        File parent = file.getParentFile();
        if (!parent.exists()) parent.mkdirs();
        Files.write(file.toPath(), xmlContent.getBytes(StandardCharsets.UTF_8));
    }

    public static String loadXml(String filePath) throws IOException {
        return new String(Files.readAllBytes(Paths.get(filePath)), StandardCharsets.UTF_8);
    }
	
	public static Path getFilePath (		
		String smjer,
		String porezniBrojIliOib,
		String tipCode,
		String nazivDokumenta,
        int vrstaDokumenta,
        int godina,
        String brojEracuna,
        LocalDateTime issueDateTime, Long electronicId) throws IOException{
		
		Path propsPath = Paths.get(Configs.eracun); // putanja do property datoteke
		EracunSyncConfig cfg = new EracunSyncConfig(propsPath);		
		Path baseDir = Paths.get(cfg.baseDir());
		
		String posrednikCode = PosrednikType.fromId(cfg.posrednikId()).getCode();	
		String safeNazivDok = sanitizeForFile(nazivDokumenta);
		String safeVrstaDok = sanitizeForFile(Integer.toString(vrstaDokumenta));
		String safeBroj     = sanitizeForFile(brojEracuna);
		
		if(electronicId == null) electronicId = 0L;

		String prefix = "ulazni".equalsIgnoreCase(smjer)
			? porezniBrojIliOib
            : ("HR" + porezniBrojIliOib);

		String ts = issueDateTime != null
            ? issueDateTime.format(java.time.format.DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss"))
            : java.time.LocalDateTime.now().format(java.time.format.DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss"));

		String fileName = prefix + "_" + tipCode + "_" + safeNazivDok + "_" + safeVrstaDok + "_" +
            godina + "_" + safeBroj + "_" + ts + "_" + electronicId;		
		
		if(godina == 0){
			fileName = fileName + "_" + (int)(Math.random() * 10000);
		}		
		fileName = fileName + ".xml";
		String godinaString = Integer.toString(godina);
		Path dir = baseDir.resolve(posrednikCode).resolve(smjer).resolve(godinaString);
		Files.createDirectories(dir);
		Path filePath = dir.resolve(fileName);
		return filePath;
	}
	
	// Minimalna sanitizacija za sigurne nazive datoteka.
	private static String sanitizeForFile(String s) {
		if (s == null) return "";
		// zamijeni slash i backslash, dvotočku i nevidljive, višestruke razmake sabij
		String cleaned = s.replace('/', '-')
            .replace('\\', '-')
            .replace(':', '-')
            .replace('"', '\'')
            .replace('|', '-')
            .replace('*', '-')
            .replace('?', '-')
            .replace('<', '(')
            .replace('>', ')')
            .trim();
		// razmake zamijeni underscoreom radi konzistentnosti
		cleaned = cleaned.replaceAll("\\s+", "_");
		// ukloni kontrolne znakove
		return cleaned.replaceAll("\\p{Cntrl}", "");
	}
}