-- Migration 007: flight_actual table + schedule enrichment columns

-- ── New table: actual flight data from FR24 flight-summary/full ────────────

CREATE TABLE IF NOT EXISTS fr24_ext.flight_actual (
    id              BIGSERIAL PRIMARY KEY,
    fr24_id         VARCHAR(30) NOT NULL UNIQUE,
    flight          VARCHAR(20),
    callsign        VARCHAR(20),
    operated_as     VARCHAR(5),       -- ICAO airline code
    origin_icao     VARCHAR(5),
    dest_icao       VARCHAR(5),
    datetime_takeoff    TIMESTAMPTZ,
    datetime_landed    TIMESTAMPTZ,
    flight_time     INTEGER,          -- seconds
    runway_takeoff  VARCHAR(10),
    runway_landed   VARCHAR(10),
    actual_distance FLOAT,            -- km
    category        VARCHAR(20),      -- Passenger/Cargo/Military
    flight_ended    BOOLEAN DEFAULT false,
    first_seen      TIMESTAMPTZ,
    last_seen       TIMESTAMPTZ,
    flight_date     DATE NOT NULL,
    fetched_at      TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE INDEX IF NOT EXISTS idx_flight_actual_date ON fr24_ext.flight_actual (flight_date);
CREATE INDEX IF NOT EXISTS idx_flight_actual_flight ON fr24_ext.flight_actual (flight, flight_date);
CREATE INDEX IF NOT EXISTS idx_flight_actual_orig ON fr24_ext.flight_actual (origin_icao, flight_date);
CREATE INDEX IF NOT EXISTS idx_flight_actual_dest ON fr24_ext.flight_actual (dest_icao, flight_date);
CREATE INDEX IF NOT EXISTS idx_flight_actual_category ON fr24_ext.flight_actual (category);

-- ── Enrich schedule table with actual times + delays ────────────────────────

ALTER TABLE fr24_ext.schedule
    ADD COLUMN IF NOT EXISTS actual_takeoff   TIMESTAMPTZ,
    ADD COLUMN IF NOT EXISTS actual_landed    TIMESTAMPTZ,
    ADD COLUMN IF NOT EXISTS delay_takeoff_min INTEGER,
    ADD COLUMN IF NOT EXISTS delay_landed_min  INTEGER,
    ADD COLUMN IF NOT EXISTS fr24_id          VARCHAR(30),
    ADD COLUMN IF NOT EXISTS flight_category  VARCHAR(20);

CREATE INDEX IF NOT EXISTS idx_schedule_fr24_id ON fr24_ext.schedule (fr24_id);

COMMENT ON TABLE fr24_ext.flight_actual IS 'Actual flight data from FR24 flight-summary/full endpoint';
