-- ============================================================
-- Migration 021: Auditoria e conteúdos da IA
-- Tabelas:
--   admin_audit_logs
--   ai_knowledge_contents
-- ============================================================

CREATE TABLE IF NOT EXISTS admin_audit_logs (
  id SERIAL PRIMARY KEY,
  actor_user_id INTEGER REFERENCES usuarios(id) ON DELETE SET NULL,
  actor_name VARCHAR(180),
  action VARCHAR(120) NOT NULL,
  target_type VARCHAR(80),
  target_id VARCHAR(120),
  details TEXT,
  created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX IF NOT EXISTS idx_admin_audit_logs_created_at
  ON admin_audit_logs (created_at DESC, id DESC);

CREATE TABLE IF NOT EXISTS ai_knowledge_contents (
  id SERIAL PRIMARY KEY,
  title VARCHAR(220) NOT NULL,
  area_id INTEGER REFERENCES areas(id) ON DELETE SET NULL,
  filename VARCHAR(260),
  mimetype VARCHAR(160),
  file_size INTEGER,
  content_base64 TEXT,
  status VARCHAR(40) NOT NULL DEFAULT 'available',
  notes TEXT,
  created_by_user_id INTEGER REFERENCES usuarios(id) ON DELETE SET NULL,
  created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX IF NOT EXISTS idx_ai_knowledge_contents_area
  ON ai_knowledge_contents (area_id, status);

CREATE INDEX IF NOT EXISTS idx_ai_knowledge_contents_created_at
  ON ai_knowledge_contents (created_at DESC, id DESC);
