-- IT0 Migration 003: Add missing tables to tenant schema template
-- Tables: users, api_keys, roles, agent_tasks, health_check_results,
--         metric_snapshots, skills, hook_scripts
-- Run this AFTER 002 for each tenant schema, or apply to existing schemas.

-- Usage: Replace {SCHEMA} with target schema name (e.g., it0_t_t001)
-- For new tenants, these tables are included automatically.

SET search_path TO {SCHEMA};

-- =========================================================================
-- AUTH TABLES
-- =========================================================================

-- Users
CREATE TABLE IF NOT EXISTS users (
    id              UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id       VARCHAR(20) NOT NULL,
    email           VARCHAR(255) NOT NULL,
    password_hash   VARCHAR(255) NOT NULL,
    name            VARCHAR(100) NOT NULL,
    roles           VARCHAR(30)[] NOT NULL DEFAULT '{viewer}',
    is_active       BOOLEAN NOT NULL DEFAULT TRUE,
    last_login_at   TIMESTAMPTZ,
    created_at      TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at      TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE UNIQUE INDEX IF NOT EXISTS idx_users_email ON users(email);
CREATE INDEX IF NOT EXISTS idx_users_active ON users(is_active) WHERE is_active = TRUE;

-- Roles (permission templates)
CREATE TABLE IF NOT EXISTS roles (
    id              UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id       VARCHAR(20) NOT NULL,
    name            VARCHAR(50) NOT NULL,
    permissions     VARCHAR(100)[] NOT NULL DEFAULT '{}',
    description     TEXT,
    created_at      TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE UNIQUE INDEX IF NOT EXISTS idx_roles_name ON roles(name);

-- API Keys
CREATE TABLE IF NOT EXISTS api_keys (
    id              UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id       VARCHAR(20) NOT NULL,
    user_id         UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    key_hash        VARCHAR(255) NOT NULL,
    name            VARCHAR(100) NOT NULL,
    permissions     VARCHAR(100)[] NOT NULL DEFAULT '{}',
    expires_at      TIMESTAMPTZ,
    last_used_at    TIMESTAMPTZ,
    is_active       BOOLEAN NOT NULL DEFAULT TRUE,
    created_at      TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_api_keys_user ON api_keys(user_id);
CREATE INDEX IF NOT EXISTS idx_api_keys_hash ON api_keys(key_hash);

-- =========================================================================
-- AGENT SERVICE - MISSING TABLES
-- =========================================================================

-- Agent Tasks (individual task prompts within a session)
CREATE TABLE IF NOT EXISTS agent_tasks (
    id              UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id       VARCHAR(20) NOT NULL,
    session_id      UUID NOT NULL REFERENCES agent_sessions(id) ON DELETE CASCADE,
    prompt          TEXT NOT NULL,
    status          VARCHAR(20) NOT NULL DEFAULT 'pending',
    result          TEXT,
    tokens_used     INTEGER,
    started_at      TIMESTAMPTZ,
    completed_at    TIMESTAMPTZ,
    created_at      TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_agent_tasks_session ON agent_tasks(session_id);
CREATE INDEX IF NOT EXISTS idx_agent_tasks_status ON agent_tasks(status) WHERE status IN ('pending', 'running');

-- Skills (agent skill definitions)
CREATE TABLE IF NOT EXISTS skills (
    id              UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id       VARCHAR(20) NOT NULL,
    name            VARCHAR(100) NOT NULL,
    category        VARCHAR(50) NOT NULL DEFAULT 'general',
    description     TEXT,
    content         TEXT NOT NULL,
    tags            VARCHAR(50)[] DEFAULT '{}',
    is_active       BOOLEAN NOT NULL DEFAULT TRUE,
    created_at      TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at      TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE UNIQUE INDEX IF NOT EXISTS idx_skills_name ON skills(name);
CREATE INDEX IF NOT EXISTS idx_skills_category ON skills(category);

-- Hook Scripts (lifecycle hooks for tool execution)
CREATE TABLE IF NOT EXISTS hook_scripts (
    id              UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id       VARCHAR(20) NOT NULL,
    name            VARCHAR(100) NOT NULL,
    event           VARCHAR(30) NOT NULL,
    tool_pattern    VARCHAR(200) NOT NULL DEFAULT '*',
    script          TEXT NOT NULL,
    timeout         INTEGER NOT NULL DEFAULT 30,
    enabled         BOOLEAN NOT NULL DEFAULT TRUE,
    description     TEXT,
    created_at      TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at      TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE UNIQUE INDEX IF NOT EXISTS idx_hook_scripts_name ON hook_scripts(name);
CREATE INDEX IF NOT EXISTS idx_hook_scripts_event ON hook_scripts(event);

-- =========================================================================
-- MONITOR SERVICE - MISSING TABLES
-- =========================================================================

-- Health Check Results
CREATE TABLE IF NOT EXISTS health_check_results (
    id              UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id       VARCHAR(20) NOT NULL,
    server_id       UUID NOT NULL,
    server_host     VARCHAR(255),
    check_type      VARCHAR(20) NOT NULL,
    status          VARCHAR(20) NOT NULL,
    latency_ms      INTEGER,
    checked_at      TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    error           TEXT,
    created_at      TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_health_checks_server ON health_check_results(server_id, checked_at DESC);
CREATE INDEX IF NOT EXISTS idx_health_checks_status ON health_check_results(status) WHERE status != 'healthy';

-- Metric Snapshots (time-series metric data)
CREATE TABLE IF NOT EXISTS metric_snapshots (
    id              BIGSERIAL PRIMARY KEY,
    tenant_id       VARCHAR(20) NOT NULL,
    server_id       UUID NOT NULL,
    metric_type     VARCHAR(50) NOT NULL,
    value           DOUBLE PRECISION NOT NULL,
    recorded_at     TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_metrics_server_type ON metric_snapshots(server_id, metric_type, recorded_at DESC);
CREATE INDEX IF NOT EXISTS idx_metrics_recorded ON metric_snapshots(recorded_at);
