package de.roko.genalogy.downloader.database;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class KreisOrtExtractor {

    private static final String DB = "archion.db";

    public void readNwrite() throws Exception {
        try (Connection conn = DriverManager.getConnection("jdbc:sqlite:" + DB)) {

            String sql = "SELECT id, archiv_id, name, link FROM kreis ORDER BY id";
            try (PreparedStatement stmt = conn.prepareStatement(sql);
                 ResultSet rs = stmt.executeQuery()) {

                while (rs.next()) {
                    int kreisId = rs.getInt("id");
                    int archivId = rs.getInt("archiv_id");
                    String name = rs.getString("name");
                    String link = rs.getString("link");

                    System.out.println("\n🔎 Lade Orte unter Kirchenkreis: " + name);

                    List<Ort> orte = extractOrte(archivId, kreisId, link);
                    saveOrte(orte, conn);

                    System.out.println("→ " + orte.size() + " Orte gespeichert.");
                }
            }
        }
    }

    private List<Ort> extractOrte(int archivId, int kreisId, String url) {
        List<Ort> orte = new ArrayList<>();
        try {
            Document doc = Jsoup.connect(url).get();
            Elements items = doc.select("#archive-nav li.item a");

            for (Element linkEl : items) {
                String name = linkEl.text().trim();
                String href = linkEl.absUrl("href").trim();
                if (!name.isEmpty() && !href.isEmpty()) {
                    orte.add(new Ort(archivId, kreisId, name, href));
                }
            }
        } catch (Exception e) {
            System.err.println("⚠️ Fehler bei URL " + url + ": " + e.getMessage());
        }
        return orte;
    }

    private void saveOrte(List<Ort> list, Connection conn) throws SQLException {
        String sql = """
            INSERT INTO ort (archiv_id, kreis_id, name, link)
            VALUES (?, ?, ?, ?)
            ON CONFLICT(archiv_id, name)
            DO UPDATE SET link = excluded.link, kreis_id = excluded.kreis_id;
            """;
        try (PreparedStatement stmt = conn.prepareStatement(sql)) {
            for (Ort o : list) {
                stmt.setInt(1, o.archivId());
                stmt.setInt(2, o.kreisId());
                stmt.setString(3, o.name());
                stmt.setString(4, o.link());
                stmt.addBatch();
            }
            stmt.executeBatch();
        }
    }

    public record Ort(int archivId, int kreisId, String name, String link) {}
}
