package com.andrewlalis.perfin.data.impl;

import com.andrewlalis.perfin.data.SavedQueryRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collections;
import java.util.List;

public record FileSystemSavedQueryRepository(Path contentDir) implements SavedQueryRepository {
    private static final Logger log = LoggerFactory.getLogger(FileSystemSavedQueryRepository.class);

    private Path queriesDir() {
        return contentDir.resolve("saved-queries");
    }

    private Path queryFile(String name) {
        return queriesDir().resolve(name + ".sql");
    }

    @Override
    public List<String> getSavedQueries() {
        Path dir = queriesDir();
        if (Files.notExists(dir)) return Collections.emptyList();
        try (var stream = Files.list(dir)) {
            return stream.filter(p ->
                    Files.isRegularFile(p) &&
                    p.getFileName().toString().toLowerCase().endsWith(".sql")
                )
                .map(p -> {
                    var s = p.getFileName().toString();
                    int idx = s.lastIndexOf('.');
                    return s.substring(0, idx);
                })
                .sorted()
                .toList();
        } catch (IOException e) {
            log.error("Failed to list files", e);
            return Collections.emptyList();
        }
    }

    @Override
    public String getSavedQueryContent(String name) {
        Path file = queryFile(name);
        if (Files.notExists(file)) return null;
        try {
            return Files.readString(file);
        } catch (IOException e) {
            log.error("Failed to read saved query content", e);
            return null;
        }
    }

    @Override
    public void createSavedQuery(String name, String content) {
        try {
            if (Files.notExists(queriesDir())) {
                Files.createDirectory(queriesDir());
            }
            Path file = queryFile(name);
            Files.writeString(file, content);
        } catch (IOException e) {
            log.error("Failed to create saved query.", e);
        }
    }

    @Override
    public void deleteSavedQuery(String name) {
        try {
            Files.deleteIfExists(queryFile(name));
        } catch (IOException e) {
            log.error("Failed to delete saved query.");
        }
    }
}
