-- +goose Up
-- +goose StatementBegin

-- WireGuard peers. v1 uses Option A (shared server identity, see
-- docs/architecture.md §8.1) — the local server peer is row 1, type
-- 'server'; remote site-to-site peers and road-warrior clients are
-- separate rows.
--
-- private_key_enc holds the encrypted server private key (NULL for
-- non-server rows); decryption key lives in /var/lib/edgeguard/.wg_key
-- (mode 0600). Never logged.
CREATE TABLE IF NOT EXISTS wireguard_peers (
    id                    BIGSERIAL PRIMARY KEY,
    name                  TEXT NOT NULL,
    peer_type             TEXT NOT NULL,
    public_key            TEXT NOT NULL,
    private_key_enc       TEXT,
    preshared_key_enc     TEXT,
    allowed_ips           TEXT NOT NULL,
    endpoint              TEXT,
    listen_port           INTEGER,
    persistent_keepalive  INTEGER,
    last_handshake_at     TIMESTAMPTZ,
    active                BOOLEAN NOT NULL DEFAULT TRUE,
    notes                 TEXT,
    created_at            TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at            TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    CONSTRAINT wireguard_peers_name_unique     UNIQUE (name),
    CONSTRAINT wireguard_peers_pubkey_unique   UNIQUE (public_key),
    CONSTRAINT wireguard_peers_type_check      CHECK (peer_type IN ('server', 's2s', 'roadwarrior'))
);

CREATE INDEX IF NOT EXISTS idx_wireguard_peers_active ON wireguard_peers (active) WHERE active;
CREATE INDEX IF NOT EXISTS idx_wireguard_peers_type   ON wireguard_peers (peer_type);

-- +goose StatementEnd

-- +goose Down
-- +goose StatementBegin
DROP TABLE IF EXISTS wireguard_peers;
-- +goose StatementEnd
