-- Phase 13 — Ecosystem Integrations
-- Run AFTER 012_stripe_payments.sql
SET FOREIGN_KEY_CHECKS = 0;

CREATE TABLE IF NOT EXISTS integrations (
  id            INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  tenant_id     INT UNSIGNED NOT NULL,
  provider      VARCHAR(50)  NOT NULL,
  status        ENUM('active','inactive','error') DEFAULT 'inactive',
  settings      JSON         DEFAULT NULL,
  last_sync     DATETIME     DEFAULT NULL,
  error_message TEXT         DEFAULT NULL,
  created_by    INT UNSIGNED DEFAULT NULL,
  created_at    DATETIME     DEFAULT NOW(),
  updated_at    DATETIME     ON UPDATE NOW(),
  UNIQUE KEY uk_tenant_provider (tenant_id, provider),
  INDEX idx_tenant (tenant_id),
  CONSTRAINT fk_integ_tenant FOREIGN KEY (tenant_id) REFERENCES tenants(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE IF NOT EXISTS webhook_events (
  id          INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  tenant_id   INT UNSIGNED DEFAULT NULL,
  provider    VARCHAR(50)  DEFAULT NULL,
  event_type  VARCHAR(100) DEFAULT NULL,
  payload     JSON         DEFAULT NULL,
  status      ENUM('pending','processed','failed') DEFAULT 'pending',
  error       TEXT         DEFAULT NULL,
  created_at  DATETIME     DEFAULT NOW(),
  INDEX idx_provider (provider, status),
  INDEX idx_tenant   (tenant_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

SET FOREIGN_KEY_CHECKS = 1;
