-- Operating conditions: per-profile tree of stations (radios) → antennas →
-- bands. Used to auto-populate MY_RIG / MY_ANTENNA on each logged QSO
-- based on the current band, so the operator doesn't have to retype them.
--
-- Tree shape:
--   profile
--     └── station   (one row per radio: name + ADIF MY_RIG value)
--         └── antenna  (one row per antenna for that radio: name + ADIF MY_ANTENNA)
--             └── band  (band tags the antenna covers; one may be flagged default)
--
-- "Default for a band" is a per-profile flag: when the user picks 20m in the
-- entry strip and an antenna on 20m is marked default, MY_RIG and MY_ANTENNA
-- auto-fill from that antenna and its parent station. At most one antenna
-- can be the default for any given (profile, band) — enforced by a partial
-- unique index below.

CREATE TABLE operating_stations (
    id           INTEGER PRIMARY KEY AUTOINCREMENT,
    profile_id   INTEGER NOT NULL,
    name         TEXT NOT NULL,                  -- display name, e.g. "Flex 8600"
    adif_rig     TEXT NOT NULL DEFAULT '',       -- value written to MY_RIG ADIF field
    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
);
CREATE INDEX idx_operating_stations_profile ON operating_stations(profile_id, sort_order);

CREATE TABLE operating_antennas (
    id           INTEGER PRIMARY KEY AUTOINCREMENT,
    station_id   INTEGER NOT NULL,
    name         TEXT NOT NULL,                  -- e.g. "UB640 VL2.3"
    adif_ant     TEXT NOT NULL DEFAULT '',       -- value written to MY_ANTENNA ADIF field
    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
);
CREATE INDEX idx_operating_antennas_station ON operating_antennas(station_id, sort_order);

-- The bands an antenna covers. Composite PK = one row per (antenna, band).
-- is_default = the entry-form autofill picks this row when the user sets band.
CREATE TABLE operating_antenna_bands (
    antenna_id   INTEGER NOT NULL,
    band         TEXT NOT NULL,                  -- ADIF lowercase, e.g. "20m"
    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);
