-- v2.0.0: BooCoder schema — pending changes, tasks, agent registry.
-- Applied on startup by apps/coder/src/db.ts:applySchema().
-- Lives in the same 'boochat' database as BooChat's tables.

CREATE TABLE IF NOT EXISTS pending_changes (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  session_id UUID NOT NULL,
  task_id UUID,
  file_path TEXT NOT NULL,
  operation TEXT NOT NULL,
  diff TEXT NOT NULL,
  status TEXT NOT NULL DEFAULT 'pending',
  created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(),
  CONSTRAINT pending_changes_operation_chk CHECK (operation IN ('create', 'edit', 'delete')),
  CONSTRAINT pending_changes_status_chk CHECK (status IN ('pending', 'applied', 'rejected', 'reverted'))
);

CREATE TABLE IF NOT EXISTS tasks (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  project_id UUID NOT NULL,
  parent_task_id UUID REFERENCES tasks(id),
  state TEXT NOT NULL DEFAULT 'pending',
  input TEXT NOT NULL,
  output_summary TEXT,
  agent TEXT,
  model TEXT,
  execution_path TEXT,
  worktree_path TEXT,
  cost_tokens INTEGER,
  started_at TIMESTAMPTZ,
  ended_at TIMESTAMPTZ,
  created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(),
  CONSTRAINT tasks_state_chk CHECK (state IN ('pending', 'running', 'completed', 'failed', 'blocked', 'cancelled')),
  CONSTRAINT tasks_execution_path_chk CHECK (execution_path IS NULL OR execution_path IN ('native', 'acp', 'pty'))
);

CREATE TABLE IF NOT EXISTS available_agents (
  name TEXT PRIMARY KEY,
  install_path TEXT,
  version TEXT,
  supports_acp BOOLEAN NOT NULL DEFAULT false,
  supports_mcp_client BOOLEAN NOT NULL DEFAULT false,
  last_probed_at TIMESTAMPTZ
);

-- Human inbox: tasks needing attention
CREATE OR REPLACE VIEW human_inbox AS
  SELECT * FROM tasks WHERE state IN ('blocked', 'failed');
