-- 009: impressão (impressoras, log de impressões) e URL de consulta pública da NFC-e.
CREATE TABLE printers (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
  company_id BIGINT UNSIGNED NOT NULL,
  store_id BIGINT UNSIGNED NOT NULL,
  name VARCHAR(80) NOT NULL,
  type ENUM('THERMAL_58','THERMAL_80','A4') NOT NULL DEFAULT 'THERMAL_80',
  connection ENUM('BROWSER','WEBUSB') NOT NULL DEFAULT 'BROWSER',
  charset ENUM('CP850','CP860') NOT NULL DEFAULT 'CP850',
  columns_count TINYINT UNSIGNED NULL COMMENT 'Colunas de texto; padrão 48 (80mm) ou 32 (58mm)',
  qr_module_size TINYINT UNSIGNED NOT NULL DEFAULT 4,
  use_for SET('RECEIPT','FISCAL','REPORT') NOT NULL DEFAULT 'RECEIPT,FISCAL,REPORT',
  is_default TINYINT(1) NOT NULL DEFAULT 0,
  auto_print TINYINT(1) NOT NULL DEFAULT 1,
  auto_cut TINYINT(1) NOT NULL DEFAULT 1,
  drawer_mode ENUM('NEVER','CASH_ONLY','ALWAYS') NOT NULL DEFAULT 'CASH_ONLY',
  active TINYINT(1) NOT NULL DEFAULT 1,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  UNIQUE KEY uq_printers_name (store_id, name),
  KEY idx_printers_store (store_id, active),
  CONSTRAINT fk_printers_company FOREIGN KEY (company_id) REFERENCES companies (id),
  CONSTRAINT fk_printers_store FOREIGN KEY (store_id) REFERENCES stores (id)
);
CREATE TABLE print_jobs (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
  company_id BIGINT UNSIGNED NOT NULL,
  store_id BIGINT UNSIGNED NULL,
  printer_id BIGINT UNSIGNED NULL,
  document_type ENUM('RECEIPT','DANFE','TEST') NOT NULL,
  reference_type VARCHAR(30) NULL,
  reference_id BIGINT UNSIGNED NULL,
  copy_number INT UNSIGNED NOT NULL DEFAULT 1,
  user_id BIGINT UNSIGNED NULL,
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  KEY idx_print_jobs_ref (document_type, reference_id),
  KEY idx_print_jobs_date (company_id, created_at),
  CONSTRAINT fk_pj_company FOREIGN KEY (company_id) REFERENCES companies (id),
  CONSTRAINT fk_pj_printer FOREIGN KEY (printer_id) REFERENCES printers (id) ON DELETE SET NULL
);
ALTER TABLE fiscal_settings
  ADD COLUMN consult_url VARCHAR(255) NULL COMMENT 'URL de consulta pública por chave de acesso (grupo infNFeSupl/urlChave), publicada pela UF' AFTER qr_base_url;
