-- Navi Provider Control Tower foundation.
-- Stores category readiness modes and provider integration configuration.
-- Secret values are intentionally not represented; only vault reference names are stored.

CREATE TYPE "CategoryOperatingMode" AS ENUM (
  'DISABLED',
  'MARKETING_ONLY',
  'INQUIRY_ONLY',
  'DEMO_ONLY',
  'SANDBOX_READY',
  'LIVE_READY'
);

CREATE TYPE "ProviderIntegrationEnvironment" AS ENUM (
  'DEMO',
  'SANDBOX',
  'PRODUCTION'
);

CREATE TYPE "ProviderIntegrationHealthStatus" AS ENUM (
  'UNKNOWN',
  'HEALTHY',
  'DEGRADED',
  'DOWN',
  'DISABLED'
);

ALTER TABLE "Category"
  ADD COLUMN "operatingMode" "CategoryOperatingMode" NOT NULL DEFAULT 'MARKETING_ONLY',
  ADD COLUMN "modeUpdatedAt" TIMESTAMP(3),
  ADD COLUMN "modeUpdatedById" TEXT;

CREATE TABLE "ProviderIntegration" (
  "id" TEXT NOT NULL,
  "name" TEXT NOT NULL,
  "categoryKind" "CategoryKind" NOT NULL,
  "environment" "ProviderIntegrationEnvironment" NOT NULL DEFAULT 'DEMO',
  "apiBaseUrl" TEXT,
  "webhookUrl" TEXT,
  "vaultSecretRef" TEXT,
  "enabled" BOOLEAN NOT NULL DEFAULT false,
  "bookingEnabled" BOOLEAN NOT NULL DEFAULT false,
  "paymentEnabled" BOOLEAN NOT NULL DEFAULT false,
  "refundEnabled" BOOLEAN NOT NULL DEFAULT false,
  "commissionEnabled" BOOLEAN NOT NULL DEFAULT false,
  "inquiryOnly" BOOLEAN NOT NULL DEFAULT true,
  "sandboxReady" BOOLEAN NOT NULL DEFAULT false,
  "liveReady" BOOLEAN NOT NULL DEFAULT false,
  "healthStatus" "ProviderIntegrationHealthStatus" NOT NULL DEFAULT 'UNKNOWN',
  "lastSyncAt" TIMESTAMP(3),
  "lastHealthCheckAt" TIMESTAMP(3),
  "errorMessage" TEXT,
  "createdById" TEXT,
  "updatedById" TEXT,
  "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
  "updatedAt" TIMESTAMP(3) NOT NULL,

  CONSTRAINT "ProviderIntegration_pkey" PRIMARY KEY ("id")
);

CREATE UNIQUE INDEX "ProviderIntegration_name_categoryKind_environment_key"
  ON "ProviderIntegration"("name", "categoryKind", "environment");

CREATE INDEX "ProviderIntegration_categoryKind_environment_enabled_idx"
  ON "ProviderIntegration"("categoryKind", "environment", "enabled");

CREATE INDEX "ProviderIntegration_healthStatus_idx"
  ON "ProviderIntegration"("healthStatus");

ALTER TABLE "ProviderIntegration"
  ADD CONSTRAINT "ProviderIntegration_createdById_fkey"
  FOREIGN KEY ("createdById") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;

ALTER TABLE "ProviderIntegration"
  ADD CONSTRAINT "ProviderIntegration_updatedById_fkey"
  FOREIGN KEY ("updatedById") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
