-- +goose Up
-- +goose StatementBegin

-- Off-Site-Backup-Targets. Nach erfolgreichem lokalen Backup wird der
-- tarball in jeden aktiven Target hochgeladen. Schutz gegen Total-
-- Loss (Box brennt, Dump-Disk fällt aus, etc.).
--
-- kind:
--   s3   — beliebige S3-API: AWS, MinIO, Backblaze B2, Cloudflare R2,
--          Hetzner Object Storage. settings: endpoint, region, bucket,
--          access_key, secret_key, path_prefix, use_ssl.
--   sftp — klassisches SSH/SFTP. settings: host, port, username,
--          password ODER private_key (base64), remote_dir,
--          host_key_fingerprint (sha256:..., optional).

CREATE TABLE IF NOT EXISTS backup_remotes (
    id              BIGSERIAL PRIMARY KEY,
    name            TEXT NOT NULL UNIQUE,
    kind            TEXT NOT NULL,
    target_url      TEXT NOT NULL,         -- s3://bucket bzw. sftp://user@host:port
    settings        JSONB NOT NULL DEFAULT '{}'::jsonb,
    active          BOOLEAN NOT NULL DEFAULT TRUE,
    last_upload_at  TIMESTAMPTZ,
    last_error      TEXT,
    created_at      TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at      TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    CONSTRAINT backup_remotes_kind_check CHECK (kind IN ('s3', 'sftp'))
);

CREATE INDEX IF NOT EXISTS idx_backup_remotes_active
    ON backup_remotes (active) WHERE active;

-- Pro Backup: Liste der Upload-Versuche als JSONB. Format:
-- [{remote_id, remote_name, ok, size, duration_ms, error}, ...]
ALTER TABLE backups
    ADD COLUMN IF NOT EXISTS remote_uploads JSONB NOT NULL DEFAULT '[]'::jsonb;

-- +goose StatementEnd

-- +goose Down
-- +goose StatementBegin
ALTER TABLE backups DROP COLUMN IF EXISTS remote_uploads;
DROP TABLE IF EXISTS backup_remotes;
-- +goose StatementEnd
