CREATE EXTENSION IF NOT EXISTS postgis;

CREATE TABLE IF NOT EXISTS airports (
    icao TEXT PRIMARY KEY NOT NULL,
    iata TEXT,
    local TEXT,
    name TEXT NOT NULL,
    category TEXT NOT NULL,
    iso_country TEXT NOT NULL,
    iso_region TEXT NOT NULL,
    municipality TEXT NOT NULL,
    elevation_ft REAL NOT NULL,
    longitude REAL NOT NULL,
    latitude REAL NOT NULL,
    geometry GEOMETRY(POINT, 4326) NOT NULL,
    has_tower BOOLEAN DEFAULT false,
    has_beacon BOOLEAN DEFAULT false,
    public BOOLEAN DEFAULT false,
    metar_observation_time TIMESTAMPTZ
);

CREATE INDEX ON airports (iata);
CREATE INDEX ON airports (local);
CREATE INDEX ON airports (name);
CREATE INDEX ON airports (category);
CREATE INDEX ON airports (iso_country);
CREATE INDEX ON airports (iso_region);
CREATE INDEX ON airports (municipality);
CREATE INDEX ON airports USING GIST(geometry);
CREATE INDEX ON airports (metar_observation_time);

CREATE TABLE IF NOT EXISTS runways (
    id UUID PRIMARY KEY NOT NULL,
    icao TEXT NOT NULL REFERENCES airports(icao) ON DELETE CASCADE,
    runway_id TEXT NOT NULL,
    length_ft REAL NOT NULL,
    width_ft REAL NOT NULL,
    surface TEXT NOT NULL
);

CREATE INDEX ON runways (icao);
CREATE INDEX ON runways (runway_id);

CREATE TABLE IF NOT EXISTS communications (
    id UUID PRIMARY KEY NOT NULL,
    icao TEXT NOT NULL REFERENCES airports(icao) ON DELETE CASCADE,
    frequency_id TEXT NOT NULL,
    name TEXT,
    frequencies_mhz REAL[] NOT NULL,
    phone TEXT
);

CREATE INDEX ON communications (icao);
CREATE INDEX ON communications (frequency_id);
CREATE INDEX ON communications (name);

CREATE TABLE IF NOT EXISTS metars (
    icao TEXT NOT NULL,
    observation_time TIMESTAMPTZ NOT NULL,
    raw_text TEXT NOT NULL,
    data JSONB NOT NULL,
    PRIMARY KEY(icao, observation_time)
);

CREATE INDEX ON metars (observation_time DESC);

CREATE TABLE IF NOT EXISTS users (
    id UUID UNIQUE NOT NULL,
    email TEXT NOT NULL,
    email_verified BOOLEAN NOT NULL DEFAULT false,
    password_hash TEXT NOT NULL,
    role TEXT NOT NULL,
    first_name TEXT NOT NULL,
    last_name TEXT NOT NULL,
    avatar TEXT,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    PRIMARY KEY(email)
);
