<?php

declare(strict_types=1);

namespace App\Infrastructure\GeoIp;

use PDO;

final readonly class DatabaseSetup
{
    private PDO $database;

    public function __construct(string $databasePath)
    {
        $this->database = $this->initializeDatabase($databasePath);
    }

    public function setupCompleteDatabase(): void
    {
        echo "=== GeoIP-Datenbank Setup ===\n";

        // 1. Länderdaten laden
        echo "Schritt 1: Lade Länderdaten...\n";
        $countryService = new CountryDataService($this->database);
        $countryService->loadCountryData();

        // 2. IP-Ranges laden
        echo "Schritt 2: Lade IP-Ranges...\n";
        $ipRangeService = new IpRangeService($this->database);
        $ipRangeService->loadIpRanges();

        echo "Setup abgeschlossen!\n";
    }

    public function setupCountryDataOnly(): void
    {
        echo "=== Länderdaten Setup ===\n";
        $countryService = new CountryDataService($this->database);
        $countryService->loadCountryData();
        echo "Länderdaten Setup abgeschlossen!\n";
    }

    public function setupIpRangesOnly(): void
    {
        echo "=== IP-Ranges Setup ===\n";
        $ipRangeService = new IpRangeService($this->database);
        $ipRangeService->loadIpRanges();
        echo "IP-Ranges Setup abgeschlossen!\n";
    }

    private function initializeDatabase(string $file): PDO
    {
        $directory = dirname($file);
        if (! is_dir($directory)) {
            mkdir($directory, 0755, true);
        }

        $db = new PDO('sqlite:' . $file);
        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        // IP-Ranges Tabelle
        $db->exec('CREATE TABLE IF NOT EXISTS ip_ranges (
            id INTEGER PRIMARY KEY,
            ip_start INTEGER,
            ip_end INTEGER,
            country TEXT
        )');
        $db->exec('CREATE INDEX IF NOT EXISTS idx_ip_range ON ip_ranges (ip_start, ip_end)');

        // Länder-Tabelle für ISO-Daten
        $db->exec('CREATE TABLE IF NOT EXISTS countries (
            code TEXT PRIMARY KEY,
            name_en TEXT,
            name_de TEXT,
            name_native TEXT,
            updated_at TEXT
        )');

        return $db;
    }
}
