CREATE TABLE IF NOT EXISTS usuarios (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    nome VARCHAR(150) NOT NULL,
    email VARCHAR(150) NOT NULL,
    senha VARCHAR(255) NOT NULL,
    perfil ENUM('admin', 'atendente', 'gestor') NOT NULL DEFAULT 'atendente',
    status ENUM('ativo', 'inativo') NOT NULL DEFAULT 'ativo',
    ultimo_login_em DATETIME NULL,
    data_criacao DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    data_atualizacao DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE KEY uq_usuarios_email (email),
    KEY idx_usuarios_status (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS clientes (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    nome_fantasia VARCHAR(150) NOT NULL,
    razao_social VARCHAR(200) NULL,
    documento VARCHAR(20) NULL,
    email VARCHAR(150) NULL,
    telefone VARCHAR(30) NULL,
    nome_responsavel VARCHAR(150) NULL,
    status ENUM('ativo', 'inativo') NOT NULL DEFAULT 'ativo',
    observacoes TEXT NULL,
    data_criacao DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    data_atualizacao DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    KEY idx_clientes_status (status),
    KEY idx_clientes_nome_fantasia (nome_fantasia),
    KEY idx_clientes_documento (documento)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS contatos (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    cliente_id INT UNSIGNED NOT NULL,
    nome VARCHAR(150) NOT NULL,
    email VARCHAR(150) NULL,
    telefone VARCHAR(30) NULL,
    cargo VARCHAR(100) NULL,
    principal TINYINT(1) NOT NULL DEFAULT 0,
    status ENUM('ativo', 'inativo') NOT NULL DEFAULT 'ativo',
    data_criacao DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    data_atualizacao DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    KEY idx_contatos_cliente_id (cliente_id),
    KEY idx_contatos_status (status),
    CONSTRAINT fk_contatos_cliente
        FOREIGN KEY (cliente_id) REFERENCES clientes(id)
        ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS categorias (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    nome VARCHAR(120) NOT NULL,
    descricao TEXT NULL,
    cor VARCHAR(20) NULL,
    status ENUM('ativo', 'inativo') NOT NULL DEFAULT 'ativo',
    data_criacao DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    data_atualizacao DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    KEY idx_categorias_status (status),
    KEY idx_categorias_nome (nome)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS chamados (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    numero VARCHAR(30) NOT NULL,
    cliente_id INT UNSIGNED NOT NULL,
    contato_id INT UNSIGNED NULL,
    categoria_id INT UNSIGNED NULL,
    usuario_responsavel_id INT UNSIGNED NULL,
    titulo VARCHAR(200) NOT NULL,
    descricao TEXT NOT NULL,
    prioridade ENUM('baixa', 'media', 'alta', 'critica') NOT NULL DEFAULT 'media',
    status ENUM('aberto', 'em_andamento', 'aguardando_cliente', 'aguardando_interno', 'resolvido', 'cancelado') NOT NULL DEFAULT 'aberto',
    origem ENUM('manual', 'email', 'portal', 'telefone', 'whatsapp') NOT NULL DEFAULT 'manual',
    data_abertura DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    data_primeira_resposta DATETIME NULL,
    data_resolucao DATETIME NULL,
    data_vencimento_sla DATETIME NULL,
    data_criacao DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    data_atualizacao DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE KEY uq_chamados_numero (numero),
    KEY idx_chamados_cliente_id (cliente_id),
    KEY idx_chamados_contato_id (contato_id),
    KEY idx_chamados_categoria_id (categoria_id),
    KEY idx_chamados_usuario_responsavel_id (usuario_responsavel_id),
    KEY idx_chamados_status (status),
    KEY idx_chamados_prioridade (prioridade),
    KEY idx_chamados_data_abertura (data_abertura),
    KEY idx_chamados_data_vencimento_sla (data_vencimento_sla),
    CONSTRAINT fk_chamados_cliente
        FOREIGN KEY (cliente_id) REFERENCES clientes(id),
    CONSTRAINT fk_chamados_contato
        FOREIGN KEY (contato_id) REFERENCES contatos(id)
        ON DELETE SET NULL,
    CONSTRAINT fk_chamados_categoria
        FOREIGN KEY (categoria_id) REFERENCES categorias(id)
        ON DELETE SET NULL,
    CONSTRAINT fk_chamados_usuario
        FOREIGN KEY (usuario_responsavel_id) REFERENCES usuarios(id)
        ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS chamados_mensagens (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    chamado_id INT UNSIGNED NOT NULL,
    usuario_id INT UNSIGNED NULL,
    contato_id INT UNSIGNED NULL,
    tipo_autor ENUM('usuario', 'contato', 'sistema') NOT NULL DEFAULT 'usuario',
    mensagem TEXT NOT NULL,
    privado TINYINT(1) NOT NULL DEFAULT 0,
    data_criacao DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    KEY idx_chamados_mensagens_chamado_id (chamado_id),
    KEY idx_chamados_mensagens_usuario_id (usuario_id),
    KEY idx_chamados_mensagens_contato_id (contato_id),
    CONSTRAINT fk_chamados_mensagens_chamado
        FOREIGN KEY (chamado_id) REFERENCES chamados(id)
        ON DELETE CASCADE,
    CONSTRAINT fk_chamados_mensagens_usuario
        FOREIGN KEY (usuario_id) REFERENCES usuarios(id)
        ON DELETE SET NULL,
    CONSTRAINT fk_chamados_mensagens_contato
        FOREIGN KEY (contato_id) REFERENCES contatos(id)
        ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS chamados_historicos (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    chamado_id INT UNSIGNED NOT NULL,
    usuario_id INT UNSIGNED NULL,
    acao VARCHAR(150) NOT NULL,
    campo_alterado VARCHAR(100) NULL,
    valor_anterior TEXT NULL,
    valor_novo TEXT NULL,
    observacao TEXT NULL,
    data_criacao DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    KEY idx_chamados_historicos_chamado_id (chamado_id),
    KEY idx_chamados_historicos_usuario_id (usuario_id),
    KEY idx_chamados_historicos_acao (acao),
    CONSTRAINT fk_chamados_historicos_chamado
        FOREIGN KEY (chamado_id) REFERENCES chamados(id)
        ON DELETE CASCADE,
    CONSTRAINT fk_chamados_historicos_usuario
        FOREIGN KEY (usuario_id) REFERENCES usuarios(id)
        ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS anexos (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    chamado_id INT UNSIGNED NOT NULL,
    mensagem_id INT UNSIGNED NULL,
    usuario_id INT UNSIGNED NULL,
    nome_original VARCHAR(255) NOT NULL,
    nome_arquivo VARCHAR(255) NOT NULL,
    caminho VARCHAR(255) NOT NULL,
    tipo_arquivo VARCHAR(120) NULL,
    tamanho_bytes BIGINT UNSIGNED NOT NULL DEFAULT 0,
    data_criacao DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    KEY idx_anexos_chamado_id (chamado_id),
    KEY idx_anexos_mensagem_id (mensagem_id),
    KEY idx_anexos_usuario_id (usuario_id),
    CONSTRAINT fk_anexos_chamado
        FOREIGN KEY (chamado_id) REFERENCES chamados(id)
        ON DELETE CASCADE,
    CONSTRAINT fk_anexos_mensagem
        FOREIGN KEY (mensagem_id) REFERENCES chamados_mensagens(id)
        ON DELETE SET NULL,
    CONSTRAINT fk_anexos_usuario
        FOREIGN KEY (usuario_id) REFERENCES usuarios(id)
        ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS sla_regras (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    nome VARCHAR(150) NOT NULL,
    categoria_id INT UNSIGNED NULL,
    prioridade ENUM('baixa', 'media', 'alta', 'critica') NULL,
    tempo_primeira_resposta_minutos INT UNSIGNED NOT NULL DEFAULT 60,
    tempo_resolucao_minutos INT UNSIGNED NOT NULL DEFAULT 480,
    status ENUM('ativo', 'inativo') NOT NULL DEFAULT 'ativo',
    data_criacao DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    data_atualizacao DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    KEY idx_sla_regras_categoria_id (categoria_id),
    KEY idx_sla_regras_status (status),
    KEY idx_sla_regras_prioridade (prioridade),
    CONSTRAINT fk_sla_regras_categoria
        FOREIGN KEY (categoria_id) REFERENCES categorias(id)
        ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS sessoes_login (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    usuario_id INT UNSIGNED NOT NULL,
    token_sessao VARCHAR(255) NOT NULL,
    ip VARCHAR(45) NULL,
    navegador VARCHAR(255) NULL,
    data_expiracao DATETIME NULL,
    data_criacao DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    KEY idx_sessoes_login_usuario_id (usuario_id),
    KEY idx_sessoes_login_data_expiracao (data_expiracao),
    UNIQUE KEY uq_sessoes_login_token_sessao (token_sessao),
    CONSTRAINT fk_sessoes_login_usuario
        FOREIGN KEY (usuario_id) REFERENCES usuarios(id)
        ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
