-- Simplify the operating tree: drop the separate ADIF-value columns (we
-- now use the display name as the ADIF MY_RIG / MY_ANTENNA value — one
-- field per row, no duplication) and add per-rig TX power so the entry
-- strip can stamp TX_PWR alongside MY_RIG when the band changes.

-- SQLite can't DROP COLUMN safely on every version we support, so we
-- recreate the tables. operating_antenna_bands is left untouched — its
-- schema didn't change — but the FK on operating_antennas needs to be
-- rewired since the table is recreated.

DROP TABLE IF EXISTS operating_antenna_bands;

CREATE TABLE operating_stations_new (
    id           INTEGER PRIMARY KEY AUTOINCREMENT,
    profile_id   INTEGER NOT NULL,
    name         TEXT NOT NULL,
    tx_pwr       REAL,
    sort_order   INTEGER NOT NULL DEFAULT 0,
    created_at   TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
    updated_at   TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
    FOREIGN KEY (profile_id) REFERENCES station_profiles(id) ON DELETE CASCADE
);
INSERT INTO operating_stations_new (id, profile_id, name, sort_order, created_at, updated_at)
SELECT id, profile_id, name, sort_order, created_at, updated_at FROM operating_stations;
DROP TABLE operating_stations;
ALTER TABLE operating_stations_new RENAME TO operating_stations;
CREATE INDEX idx_operating_stations_profile ON operating_stations(profile_id, sort_order);

CREATE TABLE operating_antennas_new (
    id           INTEGER PRIMARY KEY AUTOINCREMENT,
    station_id   INTEGER NOT NULL,
    name         TEXT NOT NULL,
    sort_order   INTEGER NOT NULL DEFAULT 0,
    created_at   TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
    updated_at   TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
    FOREIGN KEY (station_id) REFERENCES operating_stations(id) ON DELETE CASCADE
);
INSERT INTO operating_antennas_new (id, station_id, name, sort_order, created_at, updated_at)
SELECT id, station_id, name, sort_order, created_at, updated_at FROM operating_antennas;
DROP TABLE operating_antennas;
ALTER TABLE operating_antennas_new RENAME TO operating_antennas;
CREATE INDEX idx_operating_antennas_station ON operating_antennas(station_id, sort_order);

CREATE TABLE operating_antenna_bands (
    antenna_id   INTEGER NOT NULL,
    band         TEXT NOT NULL,
    is_default   INTEGER NOT NULL DEFAULT 0,
    PRIMARY KEY (antenna_id, band),
    FOREIGN KEY (antenna_id) REFERENCES operating_antennas(id) ON DELETE CASCADE
);
CREATE INDEX idx_operating_bands_band ON operating_antenna_bands(band, is_default);
