-- Migration: Session balance mode (Mode 2)
-- Users pre-fund a Lightning session; requests auto-debit actual costs.

CREATE TABLE IF NOT EXISTS sessions (
  id                      TEXT PRIMARY KEY,
  state                   TEXT NOT NULL DEFAULT 'awaiting_payment',
  balance_sats            INTEGER NOT NULL DEFAULT 0,
  deposit_amount_sats     INTEGER NOT NULL,
  deposit_payment_hash    TEXT NOT NULL,
  deposit_payment_request TEXT NOT NULL,
  deposit_paid            BOOLEAN NOT NULL DEFAULT false,
  topup_amount_sats       INTEGER,
  topup_payment_hash      TEXT,
  topup_payment_request   TEXT,
  topup_paid              BOOLEAN,
  macaroon                TEXT,
  expires_at              TIMESTAMPTZ,
  created_at              TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  updated_at              TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE TABLE IF NOT EXISTS session_requests (
  id                TEXT PRIMARY KEY,
  session_id        TEXT NOT NULL REFERENCES sessions(id),
  request           TEXT NOT NULL,
  state             TEXT NOT NULL DEFAULT 'processing',
  result            TEXT,
  reason            TEXT,
  error_message     TEXT,
  eval_input_tokens  INTEGER,
  eval_output_tokens INTEGER,
  work_input_tokens  INTEGER,
  work_output_tokens INTEGER,
  debited_sats       INTEGER,
  balance_after_sats INTEGER,
  btc_price_usd      REAL,
  created_at         TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  updated_at         TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
