-- Usuários do sistema (painel web / RH / gestão do tenant).
-- São distintos dos colaboradores (tabela `employees` + `employee_users` para o app).
-- Pré-requisito: tabela `tenants` já existir (ver 01_core_schema.sql).

SET NAMES utf8mb4;
USE `ponto-sas`;

CREATE TABLE IF NOT EXISTS `tenant_users` (
  `id` BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  `tenant_id` BIGINT UNSIGNED NOT NULL,
  `full_name` VARCHAR(150) NOT NULL,
  `email` VARCHAR(190) NULL COMMENT 'E-mail de login (único por tenant junto com username)',
  `username` VARCHAR(60) NOT NULL COMMENT 'Login único por tenant (pode coincidir com e-mail em outro formato)',
  `password_hash` VARCHAR(255) NOT NULL COMMENT 'Use password_hash() PHP com PASSWORD_DEFAULT (bcrypt)',
  `profile` ENUM('admin','manager','analyst','viewer') NOT NULL COMMENT 'admin: total; manager/analyst/viewer: permissões de painel',
  `status` ENUM('active','inactive') NOT NULL DEFAULT 'active',
  `notify_welcome` TINYINT(1) NOT NULL DEFAULT 0,
  `last_login_at` TIMESTAMP NULL DEFAULT NULL,
  `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,

  UNIQUE KEY `uk_tenant_users_tenant_username` (`tenant_id`, `username`),
  UNIQUE KEY `uk_tenant_users_tenant_email` (`tenant_id`, `email`),
  KEY `idx_tenant_users_tenant_status` (`tenant_id`, `status`),

  CONSTRAINT `fk_tenant_users_tenant`
    FOREIGN KEY (`tenant_id`) REFERENCES `tenants`(`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Exemplo (ajuste tenant_id): gerar hash no PHP — password_hash('sua_senha', PASSWORD_DEFAULT)
-- INSERT INTO tenant_users (tenant_id, full_name, email, username, password_hash, profile, status)
-- VALUES (1, 'Administrador', 'admin@empresa.com', 'admin', '$2y$10$...', 'admin', 'active');
