-- +goose Up

-- +goose StatementBegin

-- ntp_settings — single-row, analog dns_settings.
-- listen_addresses ist Komma-separiert; access_acl gibt die CIDR-
-- Liste die als NTP-Client erlaubt ist.
CREATE TABLE IF NOT EXISTS ntp_settings (
    id                BIGINT PRIMARY KEY DEFAULT 1,
    listen_addresses  TEXT NOT NULL DEFAULT '127.0.0.1, ::1',
    allow_acl         TEXT NOT NULL DEFAULT '127.0.0.0/8, ::1/128, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16',
    serve_clients     BOOLEAN NOT NULL DEFAULT TRUE,
    makestep_secs     NUMERIC(8,2) NOT NULL DEFAULT 1.0,
    makestep_limit    INTEGER NOT NULL DEFAULT 3,
    rtcsync           BOOLEAN NOT NULL DEFAULT TRUE,
    leapsectz         TEXT,
    updated_at        TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    CONSTRAINT ntp_settings_singleton CHECK (id = 1)
);
INSERT INTO ntp_settings (id) VALUES (1) ON CONFLICT DO NOTHING;
-- +goose StatementEnd

-- +goose StatementBegin
-- ntp_pools — upstream NTP-server/pool entries.
-- kind='pool' für Round-Robin-DNS-Names (z.B. 0.de.pool.ntp.org),
-- 'server' für Einzel-Hosts. iburst empfohlen für schnelleren Sync.
CREATE TABLE IF NOT EXISTS ntp_pools (
    id          BIGSERIAL PRIMARY KEY,
    kind        TEXT NOT NULL DEFAULT 'pool',
    address     TEXT NOT NULL,
    iburst      BOOLEAN NOT NULL DEFAULT TRUE,
    prefer      BOOLEAN NOT NULL DEFAULT FALSE,
    minpoll     INTEGER,
    maxpoll     INTEGER,
    active      BOOLEAN NOT NULL DEFAULT TRUE,
    description TEXT,
    created_at  TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at  TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    CONSTRAINT ntp_pools_kind_check CHECK (kind IN ('pool', 'server'))
);

-- Sinnvolle Defaults: 4 deutsche pool.ntp.org-Server. Operator kann
-- jederzeit eigene pools/server hinzufügen oder diese deaktivieren.
INSERT INTO ntp_pools (kind, address, iburst, description) VALUES
  ('pool', '0.de.pool.ntp.org', TRUE, 'Default upstream'),
  ('pool', '1.de.pool.ntp.org', TRUE, 'Default upstream'),
  ('pool', '2.de.pool.ntp.org', TRUE, 'Default upstream'),
  ('pool', '3.de.pool.ntp.org', TRUE, 'Default upstream')
ON CONFLICT DO NOTHING;
-- +goose StatementEnd

-- +goose StatementBegin
CREATE INDEX IF NOT EXISTS idx_ntp_pools_active ON ntp_pools (active) WHERE active;
-- +goose StatementEnd

-- +goose Down
-- +goose StatementBegin
DROP TABLE IF EXISTS ntp_pools;
DROP TABLE IF EXISTS ntp_settings;
-- +goose StatementEnd
