-- Kombex API — schema complementar
-- Execute no mesmo banco configurado em config/Config.php

SET NAMES utf8mb4;

CREATE TABLE IF NOT EXISTS `clientes_api` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `cliente_id` varchar(64) NOT NULL COMMENT 'Identificador lógico do cliente (ERP, filial, etc.)',
  `api_key` varchar(128) NOT NULL,
  `api_secret_hash` varchar(255) NOT NULL COMMENT 'password_hash() do segredo (nunca armazene api_secret em texto plano)',
  `access_token` varchar(512) DEFAULT NULL COMMENT 'Opcional / legado',
  `ativo` enum('Sim','Não') NOT NULL DEFAULT 'Sim',
  `ambiente` enum('production','desenv') NOT NULL DEFAULT 'desenv',
  `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_api_key` (`api_key`),
  KEY `idx_cliente_id` (`cliente_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS `api_webhooks` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `clientes_api_id` int(11) NOT NULL,
  `url` varchar(2048) NOT NULL,
  `eventos` varchar(255) NOT NULL DEFAULT 'status',
  `ativo` enum('Sim','Não') NOT NULL DEFAULT 'Sim',
  `secret` varchar(128) DEFAULT NULL,
  `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `idx_webhook_cliente` (`clientes_api_id`),
  CONSTRAINT `fk_api_webhooks_clientes_api` FOREIGN KEY (`clientes_api_id`) REFERENCES `clientes_api` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Se as colunas já existirem, ignore o erro e comente as linhas abaixo.
ALTER TABLE `minuta_orcamentos` ADD COLUMN `codigo_solicitacao` varchar(40) DEFAULT NULL COMMENT 'Código único API' AFTER `id`;
ALTER TABLE `minuta_orcamentos` ADD COLUMN `data_atualizacao_status` datetime DEFAULT NULL AFTER `data_criacao`;
ALTER TABLE `minuta_orcamentos` ADDCOLUMN  `cliente_id_api` VARCHAR(11) NULL AFTER `id_usuario_franqueado`;

CREATE UNIQUE INDEX `uk_minuta_codigo_solicitacao` ON `minuta_orcamentos` (`codigo_solicitacao`);

-- Cliente demo: api_key kbx_demo_api_key_001 | api_secret demo_secret_change_me
INSERT IGNORE INTO `clientes_api` (`cliente_id`, `api_key`, `api_secret_hash`, `ativo`, `ambiente`)
VALUES (
  'DEMO001',
  'kbx_demo_api_key_001',
  '$2y$10$sKMJ2t2oe2ZKvhcwiJWkZ.nMruwCkWg3e3yfmhQ/mHlkxk0e5ogqW',
  'Sim',
  'desenv'
);
