-- 03_admin.sql - Usuários, autenticação e permissões básicas

CREATE TABLE users (
  id CHAR(36) PRIMARY KEY,
  tenant_id CHAR(36) NOT NULL,
  name VARCHAR(150) NOT NULL,
  email VARCHAR(150) NOT NULL,
  password_hash VARCHAR(255) NOT NULL,
  role VARCHAR(30) NOT NULL DEFAULT 'corretor',
  active TINYINT(1) NOT NULL DEFAULT 1,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  UNIQUE KEY uq_user_email (email),
  KEY idx_user_tenant (tenant_id),
  CONSTRAINT fk_users_tenant FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE
) ENGINE=InnoDB;

-- Seed: cria usuário admin para o tenant 'uniq' (se existir)
-- Senha padrão: Admin@12345 (troque depois)
INSERT INTO users (id, tenant_id, name, email, password_hash, role, active)
SELECT
  UUID(), t.id, 'Administrador', 'admin@uniq.com',
  '$2y$10$oPhrjY0ksIelyJUlNri97.kw2C12O19qiS7F0Ong60Yq6F4KD1OhC',
  'admin', 1
FROM tenants t
WHERE t.slug = 'uniq'
  AND NOT EXISTS (SELECT 1 FROM users u WHERE u.email = 'admin@uniq.com')
LIMIT 1;
