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 OrtExtractor {

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

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

            String sql = "SELECT id, name, link FROM kreis WHERE status = 'verfügbar' ORDER BY id";
            try (PreparedStatement stmt = conn.prepareStatement(sql);
                 ResultSet rs = stmt.executeQuery()) {

                while (rs.next()) {
                    int id = rs.getInt("id");
                    String name = rs.getString("name");
                    String link = rs.getString("link");
                    System.out.println("\n🔍 Lade Orte für Kreis/Dekanat: " + name);

                    List<Ort> orte = extractOrte(id, link);
                    saveOrte(orte, conn);
                    System.out.println("→ " + orte.size() + " Orte gespeichert.");
                }
            }
        }
    }

    public static List<Ort> extractOrte(int kreisId, String url) {
        List<Ort> list = new ArrayList<>();
        try {
            Document doc = Jsoup.connect(url).get();
            Elements items = doc.select(".list li a");

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

    public static void saveOrte(List<Ort> list, Connection conn) throws SQLException {
        String sql = """
            INSERT INTO ort (kreis_id, name, link)
            VALUES (?, ?, ?)
            ON CONFLICT(kreis_id, name)
            DO UPDATE SET link = excluded.link;
            """;

        try (PreparedStatement stmt = conn.prepareStatement(sql)) {
            for (Ort o : list) {
                stmt.setInt(1, o.kreisId());
                stmt.setString(2, o.name());
                stmt.setString(3, o.link());
                stmt.addBatch();
            }
            stmt.executeBatch();
        }
    }

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