DO $$
BEGIN
  RAISE NOTICE 'Init gestartet';
END $$;

CREATE TABLE IF NOT EXISTS jobs (
    id SERIAL PRIMARY KEY,
    type TEXT NOT NULL,
    payload JSONB,
    status TEXT NOT NULL DEFAULT 'queued',
    result JSONB,
    error TEXT,
    created_at TIMESTAMP DEFAULT now(),
    updated_at TIMESTAMP DEFAULT now()
);

CREATE TABLE IF NOT EXISTS rmv_data (
    id BIGSERIAL PRIMARY KEY,
    trip_index INT NOT NULL,
    leg_index INT NOT NULL,
    linie TEXT,
    abfahrt TEXT,
    ankunft TEXT,
    von TEXT,
    nach TEXT
);

CREATE TABLE IF NOT EXISTS feeds (
    id SERIAL PRIMARY KEY,
    url TEXT NOT NULL,
    access BOOLEAN NOT NULL DEFAULT TRUE,
    last_checked TIMESTAMPTZ,
    created_at TIMESTAMP DEFAULT now()
);

-- Ensure last_checked exists when rerunning against an existing DB
ALTER TABLE IF EXISTS feeds ADD COLUMN IF NOT EXISTS last_checked TIMESTAMPTZ;

CREATE TABLE IF NOT EXISTS articles (
    id BIGSERIAL PRIMARY KEY,
    article_id TEXT NOT NULL,
    feed_id INT NOT NULL REFERENCES feeds(id) ON DELETE CASCADE,
    title TEXT NOT NULL,
    link TEXT NOT NULL,
    summary TEXT,
    image TEXT,
    image_claimed_at TIMESTAMPTZ,
    image_claimed_by TEXT,
    published_at TIMESTAMPTZ,
    created_at TIMESTAMP DEFAULT now(),
    CONSTRAINT articles_feed_link_uniq UNIQUE(feed_id, link),
    CONSTRAINT articles_article_id_uniq UNIQUE(article_id)
);

DO $$
BEGIN
  IF NOT EXISTS (SELECT 1 FROM pg_attribute WHERE attrelid = 'articles'::regclass AND attname = 'article_id') THEN
    ALTER TABLE articles ADD COLUMN article_id TEXT;
  END IF;

  IF NOT EXISTS (SELECT 1 FROM pg_attribute WHERE attrelid = 'articles'::regclass AND attname = 'image') THEN
    ALTER TABLE articles ADD COLUMN image TEXT;
  END IF;
  IF NOT EXISTS (SELECT 1 FROM pg_attribute WHERE attrelid = 'articles'::regclass AND attname = 'image_claimed_at') THEN
    ALTER TABLE articles ADD COLUMN image_claimed_at TIMESTAMPTZ;
  END IF;
  IF NOT EXISTS (SELECT 1 FROM pg_attribute WHERE attrelid = 'articles'::regclass AND attname = 'image_claimed_by') THEN
    ALTER TABLE articles ADD COLUMN image_claimed_by TEXT;
  END IF;

  IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'articles_article_id_uniq') THEN
    ALTER TABLE articles ADD CONSTRAINT articles_article_id_uniq UNIQUE(article_id);
  END IF;
END $$;

CREATE TABLE IF NOT EXISTS market_quotes (
    id BIGSERIAL PRIMARY KEY,
    instrument TEXT NOT NULL,
    bid NUMERIC NOT NULL,
    quoted_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    created_at TIMESTAMP DEFAULT now()
);

DO $$
BEGIN
  IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'market_quotes_instrument_uniq') THEN
    ALTER TABLE market_quotes ADD CONSTRAINT market_quotes_instrument_uniq UNIQUE (instrument);
  END IF;
END $$;

-- Seed feeds from CSV (expects file at /docker-entrypoint-initdb.d/data/news_rss_feeds.csv)
COPY feeds (url)
FROM '/docker-entrypoint-initdb.d/data/news_rss_feeds.csv'
WITH (FORMAT csv, HEADER true);
