#!/bin/bash
# Migration script — run once per server after deploying updated code.
# Safe to re-run: each step checks whether it is needed before acting.

DB="/4server/data/contracts.db"

# -----------------------------------------------------------------------
# Helper: check whether a column exists
# -----------------------------------------------------------------------
has_column() {
    sqlite3 "$DB" "SELECT COUNT(*) FROM pragma_table_info('containers') WHERE name='$1';"
}

# -----------------------------------------------------------------------
# Step 1 — Add columns introduced over time (silently skip if present)
# -----------------------------------------------------------------------
echo "Step 1: adding missing columns..."
sqlite3 "$DB" 2>/dev/null <<'EOF' || true
ALTER TABLE containers ADD COLUMN env_list TEXT;
EOF
sqlite3 "$DB" 2>/dev/null <<'EOF' || true
ALTER TABLE containers ADD COLUMN secret_list TEXT;
EOF
sqlite3 "$DB" 2>/dev/null <<'EOF' || true
ALTER TABLE containers ADD COLUMN utm_source text;
EOF
sqlite3 "$DB" 2>/dev/null <<'EOF' || true
ALTER TABLE containers ADD COLUMN utm_medium text;
EOF
sqlite3 "$DB" 2>/dev/null <<'EOF' || true
ALTER TABLE containers ADD COLUMN utm_campaign text;
EOF
sqlite3 "$DB" 2>/dev/null <<'EOF' || true
ALTER TABLE containers ADD COLUMN container_id CHAR(50);
EOF

# -----------------------------------------------------------------------
# Step 2 — Backfill container_id from UUID
# -----------------------------------------------------------------------
echo "Step 2: backfilling container_id from UUID..."
sqlite3 "$DB" <<'EOF'
UPDATE containers
SET container_id = UUID
WHERE container_id IS NULL OR container_id = '';
EOF

# -----------------------------------------------------------------------
# Step 3 — Backfill utm_* from old affiliate JSON (if column still exists)
# -----------------------------------------------------------------------
if [ "$(has_column affiliate)" = "1" ]; then
    echo "Step 3: backfilling utm fields from affiliate JSON..."
    sqlite3 "$DB" <<'EOF'
UPDATE containers
SET utm_source   = COALESCE(utm_source,   json_extract(affiliate, '$.utm_source')),
    utm_medium   = COALESCE(utm_medium,   json_extract(affiliate, '$.utm_medium')),
    utm_campaign = COALESCE(utm_campaign, json_extract(affiliate, '$.utm_campaign'))
WHERE affiliate IS NOT NULL AND affiliate != '';
EOF
else
    echo "Step 3: affiliate column not present — skipping utm backfill."
fi

# -----------------------------------------------------------------------
# Step 4 — Remove affiliate column via full table rebuild.
# Also adds container_id UNIQUE constraint and locks in the canonical
# column order to match init_db().
# Only runs if affiliate still exists OR container_id lacks its UNIQUE index.
# -----------------------------------------------------------------------
NEEDS_REBUILD=0
[ "$(has_column affiliate)" = "1" ] && NEEDS_REBUILD=1

# If affiliate is already gone, the rebuild already ran — no need to repeat
# (container_id UNIQUE is guaranteed by the rebuild itself)

if [ "$NEEDS_REBUILD" = "1" ]; then
    echo "Step 4: rebuilding table (remove affiliate, add container_id UNIQUE)..."
    sqlite3 "$DB" <<'EOF'
BEGIN;

CREATE TABLE containers_new (
    ID            INTEGER PRIMARY KEY AUTOINCREMENT,
    UUID          CHAR(50) UNIQUE,
    container_id  CHAR(50) UNIQUE,
    email         CHAR(100),
    expires       DATE,
    tags          TEXT,
    env           TEXT,
    image         CHAR(50),
    history       TEXT,
    comment       TEXT,
    domains       TEXT,
    status        CHAR(20),
    created       DATE,
    bump          DATE,
    secret        TEXT,
    contract      TEXT,
    git           integer,
    backup_slots  integer,
    hdd           integer,
    workers       integer,
    utm_source    text,
    utm_medium    text,
    utm_campaign  text,
    domains_slots integer,
    secret_list   TEXT,
    env_list      TEXT
);

INSERT INTO containers_new
    SELECT ID, UUID, container_id, email, expires, tags, env, image, history,
           comment, domains, status, created, bump, secret, contract, git,
           backup_slots, hdd, workers, utm_source, utm_medium, utm_campaign,
           domains_slots, secret_list, env_list
    FROM containers;

DROP TABLE containers;
ALTER TABLE containers_new RENAME TO containers;

COMMIT;
EOF
    echo "Step 4: table rebuilt."
else
    echo "Step 4: table already up to date — skipping rebuild."
fi

echo "Migration complete."
