import pg from 'pg'

const { Pool } = pg
export const pool = new Pool({ connectionString: process.env.DATABASE_URL })

export async function initDb() {
  await pool.query(`
    CREATE TABLE IF NOT EXISTS report_runs (
      id          SERIAL PRIMARY KEY,
      report_id   TEXT NOT NULL,
      report_name TEXT NOT NULL,
      user_email  TEXT NOT NULL,
      date_from   DATE,
      date_to     DATE,
      row_count   INTEGER,
      duration_ms INTEGER,
      error       TEXT,
      ran_at      TIMESTAMPTZ NOT NULL DEFAULT NOW()
    );
    CREATE INDEX IF NOT EXISTS report_runs_ran_at_idx    ON report_runs (ran_at DESC);
    CREATE INDEX IF NOT EXISTS report_runs_report_id_idx ON report_runs (report_id);

    CREATE TABLE IF NOT EXISTS forecast_sessions (
      id               SERIAL PRIMARY KEY,
      year             INTEGER NOT NULL,
      month            INTEGER NOT NULL,
      pickup_avg_rate  DECIMAL(10,2) NOT NULL DEFAULT 135.00,
      notes            TEXT,
      created_at       TIMESTAMPTZ NOT NULL DEFAULT NOW(),
      updated_at       TIMESTAMPTZ NOT NULL DEFAULT NOW(),
      UNIQUE(year, month)
    );

    CREATE TABLE IF NOT EXISTS day_overrides (
      id               SERIAL PRIMARY KEY,
      session_id       INTEGER NOT NULL REFERENCES forecast_sessions(id) ON DELETE CASCADE,
      date             DATE NOT NULL,
      pickup_rooms     INTEGER,
      pickup_avg_rate  DECIMAL(10,2),
      dry_override     DECIMAL(12,2),
      wet_override     DECIMAL(12,2),
      actual_accomm    DECIMAL(12,2),
      UNIQUE(session_id, date)
    );
    CREATE INDEX IF NOT EXISTS idx_day_overrides_session ON day_overrides(session_id);
    CREATE INDEX IF NOT EXISTS idx_day_overrides_date    ON day_overrides(date);

    CREATE TABLE IF NOT EXISTS forecast_snapshots (
      id               SERIAL PRIMARY KEY,
      session_id       INTEGER NOT NULL REFERENCES forecast_sessions(id) ON DELETE CASCADE,
      snapshot_at      TIMESTAMPTZ NOT NULL DEFAULT NOW(),
      label            TEXT,
      forecast_rooms   INTEGER,
      forecast_accomm  DECIMAL(12,2),
      forecast_dry     DECIMAL(12,2),
      forecast_wet     DECIMAL(12,2),
      forecast_total   DECIMAL(12,2),
      otb_rooms        INTEGER,
      pickup_rooms     INTEGER,
      occ_pct          DECIMAL(5,2)
    );
    CREATE INDEX IF NOT EXISTS idx_forecast_snapshots_session ON forecast_snapshots(session_id);

    CREATE TABLE IF NOT EXISTS app_settings (
      key        TEXT PRIMARY KEY,
      value      TEXT NOT NULL DEFAULT '',
      updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
    );
  `)

  // Seed default setting keys (value stays empty until set via UI)
  await pool.query(`
    INSERT INTO app_settings (key, value) VALUES
      ('forecasting_url', ''),
      ('forecasting_api_key', '')
    ON CONFLICT (key) DO NOTHING
  `)
}

export async function getSetting(key) {
  const res = await pool.query('SELECT value FROM app_settings WHERE key = $1', [key])
  return res.rows[0]?.value || null
}
