

CREATE TABLE IF NOT EXISTS `wa_conversas` (
  `id` int NOT NULL AUTO_INCREMENT,
  `numero` varchar(40) NOT NULL,
  `nome` varchar(150) DEFAULT NULL,
  `ultima_mensagem` text DEFAULT NULL,
  `ultima_direcao` varchar(20) DEFAULT 'entrada',
  `ultima_em` datetime DEFAULT NULL,
  `nao_lidas` int NOT NULL DEFAULT 0,
  `status_atendimento` varchar(30) NOT NULL DEFAULT 'bot',
  `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
  PRIMARY KEY (`id`),
  UNIQUE KEY `numero` (`numero`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

CREATE TABLE IF NOT EXISTS `wa_mensagens` (
  `id` bigint NOT NULL AUTO_INCREMENT,
  `conversa_id` int DEFAULT NULL,
  `numero` varchar(40) NOT NULL,
  `nome` varchar(150) DEFAULT NULL,
  `direcao` varchar(20) NOT NULL,
  `tipo` varchar(30) DEFAULT 'chat',
  `mensagem` longtext DEFAULT NULL,
  `wa_message_id` varchar(150) DEFAULT NULL,
  `created_at` datetime NOT NULL DEFAULT current_timestamp(),
  PRIMARY KEY (`id`),
  KEY `conversa_id` (`conversa_id`),
  KEY `numero` (`numero`),
  CONSTRAINT `wa_mensagens_ibfk_1` FOREIGN KEY (`conversa_id`) REFERENCES `wa_conversas` (`id`) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

CREATE TABLE IF NOT EXISTS `wa_atendimentos` (
  `id` int NOT NULL AUTO_INCREMENT,
  `conversa_id` int DEFAULT NULL,
  `numero` varchar(40) NOT NULL,
  `nome` varchar(150) DEFAULT NULL,
  `status` varchar(30) NOT NULL DEFAULT 'aberto',
  `atendente` varchar(100) DEFAULT NULL,
  `observacoes` text DEFAULT NULL,
  `created_at` datetime NOT NULL DEFAULT current_timestamp(),
  `updated_at` datetime NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
  `finalized_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `conversa_id` (`conversa_id`),
  KEY `numero` (`numero`),
  CONSTRAINT `wa_atendimentos_ibfk_1` FOREIGN KEY (`conversa_id`) REFERENCES `wa_conversas` (`id`) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

CREATE TABLE IF NOT EXISTS `wa_qrcodes` (
  `id` int NOT NULL AUTO_INCREMENT,
  `status` varchar(30) NOT NULL DEFAULT 'aguardando',
  `qr_text` longtext DEFAULT NULL,
  `qr_image` longtext DEFAULT NULL,
  `updated_at` datetime NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;


CREATE TABLE IF NOT EXISTS `wa_atendentes` (
  `id` int NOT NULL AUTO_INCREMENT,
  `nome` varchar(100) NOT NULL,
  `telefone` varchar(40) NOT NULL,
  `ativo` tinyint(1) NOT NULL DEFAULT 1,
  `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
  PRIMARY KEY (`id`),
  UNIQUE KEY `telefone` (`telefone`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
