/**
 * src/db/migrations/004-add-cron-sessions-approvals.ts
 * Migration: Add cron jobs, sessions, approval requests tables
 */
import { createChildLogger } from '../../utils/logger.js';
const log = createChildLogger('db:migration:004');
// SQL statements for migration
const MIGRATION_SQL = `
-- Cron Jobs Table
CREATE TABLE IF NOT EXISTS cron_jobs (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
  name TEXT NOT NULL,
  schedule TEXT NOT NULL,
  timezone TEXT DEFAULT 'Asia/Riyadh',
  payload JSONB NOT NULL DEFAULT '{"kind": "systemEvent"}',
  delivery JSONB DEFAULT '{"mode": "announce"}',
  enabled BOOLEAN DEFAULT true,
  last_run_at TIMESTAMP WITH TIME ZONE,
  next_run_at TIMESTAMP WITH TIME ZONE NOT NULL,
  run_count INTEGER DEFAULT 0,
  created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
  updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_cron_jobs_tenant ON cron_jobs(tenant_id);
CREATE INDEX IF NOT EXISTS idx_cron_jobs_enabled ON cron_jobs(enabled) WHERE enabled = true;
CREATE INDEX IF NOT EXISTS idx_cron_jobs_next_run ON cron_jobs(next_run_at) WHERE enabled = true;

-- Cron Executions Table
CREATE TABLE IF NOT EXISTS cron_executions (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  job_id UUID NOT NULL REFERENCES cron_jobs(id) ON DELETE CASCADE,
  tenant_id UUID NOT NULL,
  executed_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
  success BOOLEAN NOT NULL,
  output TEXT,
  error TEXT,
  duration_ms INTEGER NOT NULL
);

CREATE INDEX IF NOT EXISTS idx_cron_executions_job ON cron_executions(job_id);
CREATE INDEX IF NOT EXISTS idx_cron_executions_tenant ON cron_executions(tenant_id);
CREATE INDEX IF NOT EXISTS idx_cron_executions_executed_at ON cron_executions(executed_at DESC);

-- Sessions Table
CREATE TABLE IF NOT EXISTS sessions (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
  label TEXT,
  kind TEXT NOT NULL DEFAULT 'isolated',
  status TEXT NOT NULL DEFAULT 'active',
  model TEXT,
  thinking BOOLEAN DEFAULT false,
  timeout_seconds INTEGER,
  parent_session_id UUID REFERENCES sessions(id) ON DELETE SET NULL,
  root_workspace_path TEXT NOT NULL,
  message_count INTEGER DEFAULT 0,
  created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
  updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
  last_message_at TIMESTAMP WITH TIME ZONE
);

CREATE INDEX IF NOT EXISTS idx_sessions_tenant ON sessions(tenant_id);
CREATE INDEX IF NOT EXISTS idx_sessions_status ON sessions(status);
CREATE INDEX IF NOT EXISTS idx_sessions_kind ON sessions(kind);

-- Session Messages Table
CREATE TABLE IF NOT EXISTS session_messages (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  session_id UUID NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
  role TEXT NOT NULL,
  content TEXT NOT NULL,
  tool_call_id TEXT,
  tool_name TEXT,
  created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_session_messages_session ON session_messages(session_id);
CREATE INDEX IF NOT EXISTS idx_session_messages_created_at ON session_messages(created_at);

-- Approval Requests Table
CREATE TABLE IF NOT EXISTS approval_requests (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
  session_id UUID REFERENCES sessions(id) ON DELETE SET NULL,
  tool_name TEXT NOT NULL,
  tool_args JSONB NOT NULL,
  reason TEXT NOT NULL,
  risk_level TEXT NOT NULL DEFAULT 'medium',
  status TEXT NOT NULL DEFAULT 'pending',
  requested_by TEXT NOT NULL,
  approved_by TEXT,
  approved_at TIMESTAMP WITH TIME ZONE,
  expires_at TIMESTAMP WITH TIME ZONE NOT NULL,
  created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_approval_tenant ON approval_requests(tenant_id);
CREATE INDEX IF NOT EXISTS idx_approval_session ON approval_requests(session_id);
CREATE INDEX IF NOT EXISTS idx_approval_status ON approval_requests(status);
CREATE INDEX IF NOT EXISTS idx_approval_expires ON approval_requests(expires_at) WHERE status = 'pending';
`;
export async function migrate() {
    log.info('Running migration 004: Add cron, sessions, approvals tables');
    log.info('Please run the following SQL in your Supabase SQL Editor:');
    log.info(MIGRATION_SQL);
    // Note: In production, you would use a proper migration tool or Supabase CLI
    // For now, we log the SQL for manual execution
}
export async function rollback() {
    log.info('Rollback SQL:');
    log.info(`
    DROP TABLE IF EXISTS approval_requests CASCADE;
    DROP TABLE IF EXISTS session_messages CASCADE;
    DROP TABLE IF EXISTS sessions CASCADE;
    DROP TABLE IF EXISTS cron_executions CASCADE;
    DROP TABLE IF EXISTS cron_jobs CASCADE;
  `);
}
//# sourceMappingURL=004-add-cron-sessions-approvals.js.map