package study.iot.command;

import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.List;

/**
 * 业务效果日志（append-only 文本文件）。一次 commandId 至多一条效果；
 * 重复调用是程序错误，直接抛异常而不是静默追加。
 */
public final class EffectLog {

    private final Path file;

    public EffectLog(Path file) {
        this.file = file;
    }

    public synchronized void append(String commandId, String payload) {
        if (contains(commandId)) {
            throw new IllegalStateException("duplicate effect for " + commandId);
        }
        try {
            Files.writeString(file, commandId + "\t" + payload + "\n", StandardCharsets.UTF_8,
                    StandardOpenOption.CREATE, StandardOpenOption.APPEND);
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }

    public synchronized List<String> ids() {
        if (!Files.exists(file)) {
            return List.of();
        }
        try {
            List<String> ids = new ArrayList<>();
            for (String line : Files.readAllLines(file, StandardCharsets.UTF_8)) {
                if (!line.isBlank()) {
                    ids.add(line.split("\t", 2)[0]);
                }
            }
            return ids;
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }

    public synchronized boolean contains(String commandId) {
        return ids().contains(commandId);
    }

    public Path file() {
        return file;
    }
}
