-- Schema do painel master SaaS
-- Usar InnoDB; importar no banco 'painel_master'

CREATE TABLE administradores (
    id INT AUTO_INCREMENT PRIMARY KEY,
    nome VARCHAR(255) NOT NULL,
    email VARCHAR(255) NOT NULL UNIQUE,
    senha_hash VARCHAR(255) NOT NULL,
    nivel ENUM('MASTER', 'SUPORTE') NOT NULL,
    ativo TINYINT(1) DEFAULT 1,
    criado_em TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB;

CREATE TABLE clientes (
    id INT AUTO_INCREMENT PRIMARY KEY,
    nome VARCHAR(255) NOT NULL,
    documento VARCHAR(20) NOT NULL UNIQUE,
    email VARCHAR(255) NOT NULL,
    status ENUM('ativo', 'inativo') DEFAULT 'ativo',
    criado_em TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB;

CREATE TABLE instancias (
    id INT AUTO_INCREMENT PRIMARY KEY,
    cliente_id INT NOT NULL,
    dominio VARCHAR(255) NOT NULL,
    caminho VARCHAR(255) NOT NULL,
    chave_unica VARCHAR(64) NOT NULL UNIQUE,
    status ENUM('ativa', 'suspensa', 'cancelada') DEFAULT 'ativa',
    criado_em TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (cliente_id) REFERENCES clientes(id) ON DELETE CASCADE
) ENGINE=InnoDB;

CREATE TABLE licencas (
    id INT AUTO_INCREMENT PRIMARY KEY,
    instancia_id INT NOT NULL,
    plano VARCHAR(100) NOT NULL,
    status ENUM('ATIVA', 'SUSPENSA', 'CANCELADA') DEFAULT 'ATIVA',
    data_inicio DATE NOT NULL,
    data_vencimento DATE NOT NULL,
    ultima_validacao TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    criado_em TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (instancia_id) REFERENCES instancias(id) ON DELETE CASCADE
) ENGINE=InnoDB;

CREATE TABLE auditoria (
    id INT AUTO_INCREMENT PRIMARY KEY,
    administrador_id INT NULL,
    evento VARCHAR(255) NOT NULL,
    detalhes_json JSON NOT NULL,
    ip VARCHAR(45) NOT NULL,
    criado_em TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (administrador_id) REFERENCES administradores(id) ON DELETE SET NULL
) ENGINE=InnoDB;
