-- Instance settings (#79): the first configuration that lives in the database
-- rather than the environment.
--
-- Until now every preference hung off a garden or object row; this is pansy's
-- first INSTANCE-level state. A single-row table (CHECK id = 1) is the least
-- surprising shape for "there is exactly one of these" — a key/value table would
-- invite typo'd keys and lose the column types.
--
-- Only NON-SECRET agent settings live here. OLLAMA_CLOUD_API_KEY stays in the
-- environment on purpose: a copy in SQLite would land in every backup and in the
-- blast radius of the undo history. An admin can change WHICH model runs, not
-- WHOSE account pays for it.
--
-- Both agent columns are "inherit from env unless set":
--   * agent_model = '' means fall back to PANSY_AGENT_MODEL, then the built-in
--     default. So an instance that never opens Settings behaves exactly as it
--     did before this migration, and the documented env var keeps working.
--   * agent_enabled is NULLABLE: NULL means inherit PANSY_AGENT_ENABLED's
--     behaviour (on when a key is present), 0/1 is an explicit override. A plain
--     boolean couldn't tell "admin hasn't touched this" from "admin turned it
--     off", and those must deploy differently.
--
-- version drives the same optimistic-concurrency 409 every other mutable row
-- uses, so two admins editing at once conflict rather than clobber.
CREATE TABLE instance_settings (
    id            INTEGER PRIMARY KEY CHECK (id = 1),
    agent_model   TEXT    NOT NULL DEFAULT '',
    agent_enabled INTEGER          CHECK (agent_enabled IN (0, 1)),
    version       INTEGER NOT NULL DEFAULT 1,
    updated_at    TEXT    NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now'))
);

-- Seed the single row so every read is a plain SELECT with no "does it exist
-- yet" branch. Inherits everything from the environment out of the box.
INSERT INTO instance_settings (id, agent_model, agent_enabled) VALUES (1, '', NULL);
