-- ============================================
-- MIGRACIÓN 001: Crear Schema y Tabla de Usuarios
-- ============================================
-- 
-- Crea el schema emerges_content y la tabla de usuarios
-- necesaria para autenticación del admin panel
-- 

-- Crear schema si no existe
CREATE SCHEMA IF NOT EXISTS emerges_content;

-- Tabla de usuarios
CREATE TABLE IF NOT EXISTS emerges_content.users (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  email TEXT UNIQUE NOT NULL,
  username TEXT NOT NULL,
  password_hash TEXT NOT NULL,
  role TEXT NOT NULL DEFAULT 'editor',
  is_active BOOLEAN NOT NULL DEFAULT true,
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  last_login TIMESTAMPTZ
);

-- Índices
CREATE INDEX IF NOT EXISTS idx_users_email ON emerges_content.users(email);
CREATE INDEX IF NOT EXISTS idx_users_role ON emerges_content.users(role);
CREATE INDEX IF NOT EXISTS idx_users_is_active ON emerges_content.users(is_active);

-- Trigger para actualizar updated_at
CREATE OR REPLACE FUNCTION emerges_content.update_updated_at_column()
RETURNS TRIGGER AS $$
BEGIN
  NEW.updated_at = NOW();
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER update_users_updated_at
  BEFORE UPDATE ON emerges_content.users
  FOR EACH ROW
  EXECUTE FUNCTION emerges_content.update_updated_at_column();

-- Comentarios
COMMENT ON TABLE emerges_content.users IS 'Usuarios del sistema de administración';
COMMENT ON COLUMN emerges_content.users.role IS 'Rol del usuario: super_admin, editor_clinico, editor_formativo, revisor, viewer';

