-- Tables affected: local_configuration_versions (SQLite), local_configurations (SQLite)
-- recovery.not-started: safe to re-run only if table does not exist; fails if table or column already present
-- recovery.partial: roll back: DROP TABLE IF EXISTS local_configuration_versions; run SQLite migration recovery
-- recovery.completed: no action needed
-- verify: local_configuration_versions table missing | SELECT 1 FROM sqlite_master WHERE type='table' AND name='local_configuration_versions' HAVING COUNT(*)=0

-- Add full-snapshot versioning for local configurations (SQLite)
-- 1) Create local_configuration_versions
-- 2) Add current_version_id to local_configurations
-- 3) Backfill v1 snapshots from existing local_configurations

PRAGMA foreign_keys = ON;

BEGIN TRANSACTION;

CREATE TABLE local_configuration_versions (
    id TEXT PRIMARY KEY,
    configuration_uuid TEXT NOT NULL,
    version_no INTEGER NOT NULL,
    data TEXT NOT NULL,
    change_note TEXT NULL,
    created_by TEXT NULL,
    app_version TEXT NULL,
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (configuration_uuid) REFERENCES local_configurations(uuid),
    UNIQUE(configuration_uuid, version_no)
);

ALTER TABLE local_configurations
    ADD COLUMN current_version_id TEXT NULL;

CREATE INDEX idx_lcv_config_created
    ON local_configuration_versions(configuration_uuid, created_at DESC);

CREATE INDEX idx_lcv_config_version
    ON local_configuration_versions(configuration_uuid, version_no DESC);

-- Backfill v1 snapshot for every existing configuration.
INSERT INTO local_configuration_versions (
    id,
    configuration_uuid,
    version_no,
    data,
    change_note,
    created_by,
    app_version,
    created_at
)
SELECT
    uuid || '-v1' AS id,
    uuid AS configuration_uuid,
    1 AS version_no,
    json_object(
        'uuid', uuid,
        'server_id', server_id,
        'name', name,
        'items', CASE WHEN json_valid(items) THEN json(items) ELSE items END,
        'total_price', total_price,
        'custom_price', custom_price,
        'notes', notes,
        'is_template', is_template,
        'server_count', server_count,
        'price_updated_at', price_updated_at,
        'created_at', created_at,
        'updated_at', updated_at,
        'synced_at', synced_at,
        'sync_status', sync_status,
        'original_user_id', original_user_id,
        'original_username', original_username,
        'app_version', NULL
    ) AS data,
    'Initial snapshot backfill (v1)' AS change_note,
    NULL AS created_by,
    NULL AS app_version,
    COALESCE(created_at, CURRENT_TIMESTAMP) AS created_at
FROM local_configurations;

UPDATE local_configurations
SET current_version_id = (
    SELECT lcv.id
    FROM local_configuration_versions lcv
    WHERE lcv.configuration_uuid = local_configurations.uuid
      AND lcv.version_no = 1
);

COMMIT;
