-- Tabela para gerenciar jobs de busca de vendas
CREATE TABLE IF NOT EXISTS `sales_jobs` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL,
  `marketplace` enum('shopee','mercadolivre') NOT NULL,
  `status` enum('pending','processing','completed','failed') NOT NULL DEFAULT 'pending',
  `priority` enum('low','normal','high') NOT NULL DEFAULT 'normal',
  `worker_id` varchar(255) DEFAULT NULL,
  `metadata` json DEFAULT NULL COMMENT 'Dados extras como days_back, filtros, etc',
  `result` json DEFAULT NULL COMMENT 'Resultado do processamento',
  `error_message` text DEFAULT NULL,
  `retry_count` int(11) NOT NULL DEFAULT 0,
  `created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `started_at` timestamp NULL DEFAULT NULL,
  `completed_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `idx_user_marketplace` (`user_id`, `marketplace`),
  KEY `idx_status` (`status`),
  KEY `idx_priority_created` (`priority`, `created_at`),
  KEY `idx_created_at` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Índices adicionais para performance
CREATE INDEX IF NOT EXISTS `idx_pending_priority` ON `sales_jobs` (`status`, `priority`, `created_at`) WHERE `status` = 'pending';
CREATE INDEX IF NOT EXISTS `idx_worker_processing` ON `sales_jobs` (`worker_id`, `status`) WHERE `status` = 'processing';
