-- migrate:up

-- Tabla para manejar conversaciones que requieren intervención humana
CREATE TABLE human_takeovers (
  id SERIAL PRIMARY KEY,
  tenant_id UUID NOT NULL REFERENCES tenants(id) ON DELETE CASCADE,
  chat_id TEXT NOT NULL,
  
  -- Info del takeover
  pending_query TEXT NOT NULL,              -- La query/producto que no se encontró
  reason TEXT NOT NULL DEFAULT 'product_not_found',  -- Razón del takeover
  context_snapshot JSONB,                   -- Snapshot del contexto al momento del takeover
  
  -- Estado
  status TEXT NOT NULL DEFAULT 'pending',   -- 'pending', 'responded', 'cancelled'
  
  -- Respuesta del humano
  human_response TEXT,                      -- Texto de la respuesta
  responded_at TIMESTAMPTZ,
  responded_by TEXT,                        -- Email/ID del usuario que respondió
  
  -- Metadatos
  created_at TIMESTAMPTZ DEFAULT NOW(),
  updated_at TIMESTAMPTZ DEFAULT NOW(),
  
  -- Índices
  CONSTRAINT valid_status CHECK (status IN ('pending', 'responded', 'cancelled'))
);

-- Índice para buscar takeovers pendientes por tenant
CREATE INDEX idx_takeovers_pending ON human_takeovers(tenant_id, status, created_at DESC)
WHERE status = 'pending';

-- Índice para buscar por chat_id
CREATE INDEX idx_takeovers_chat ON human_takeovers(tenant_id, chat_id, created_at DESC);

-- Función para actualizar updated_at
CREATE OR REPLACE FUNCTION update_takeover_timestamp()
RETURNS TRIGGER AS $$
BEGIN
  NEW.updated_at := NOW();
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER takeover_updated_trigger
BEFORE UPDATE ON human_takeovers
FOR EACH ROW EXECUTE FUNCTION update_takeover_timestamp();

-- migrate:down

DROP TRIGGER IF EXISTS takeover_updated_trigger ON human_takeovers;
DROP FUNCTION IF EXISTS update_takeover_timestamp();
DROP INDEX IF EXISTS idx_takeovers_chat;
DROP INDEX IF EXISTS idx_takeovers_pending;
DROP TABLE IF EXISTS human_takeovers;
