-- Full-text search: GIN index on documents for fast ts_vector queries
CREATE INDEX IF NOT EXISTS "idx_actuate_documents_fts"
  ON "actuate_documents"
  USING GIN (to_tsvector('english', COALESCE("title", '') || ' ' || COALESCE("plainText", '')));

-- Webhook endpoints table
CREATE TABLE IF NOT EXISTS "actuate_webhook_endpoints" (
    "id" TEXT NOT NULL,
    "url" TEXT NOT NULL,
    "events" JSONB NOT NULL,
    "secret" TEXT NOT NULL,
    "active" BOOLEAN NOT NULL DEFAULT true,
    "name" TEXT,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

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

-- Webhook delivery log table
CREATE TABLE IF NOT EXISTS "actuate_webhook_deliveries" (
    "id" TEXT NOT NULL,
    "endpointId" TEXT NOT NULL,
    "event" TEXT NOT NULL,
    "payload" JSONB NOT NULL,
    "status" TEXT NOT NULL DEFAULT 'pending',
    "attempts" INTEGER NOT NULL DEFAULT 0,
    "maxAttempts" INTEGER NOT NULL DEFAULT 3,
    "lastAttemptAt" TIMESTAMP(3),
    "nextRetryAt" TIMESTAMP(3),
    "responseStatus" INTEGER,
    "responseBody" TEXT,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

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

CREATE INDEX IF NOT EXISTS "actuate_webhook_deliveries_endpointId_idx"
  ON "actuate_webhook_deliveries"("endpointId");

CREATE INDEX IF NOT EXISTS "actuate_webhook_deliveries_status_idx"
  ON "actuate_webhook_deliveries"("status");

CREATE INDEX IF NOT EXISTS "actuate_webhook_deliveries_nextRetryAt_idx"
  ON "actuate_webhook_deliveries"("nextRetryAt");

ALTER TABLE "actuate_webhook_deliveries"
  ADD CONSTRAINT "actuate_webhook_deliveries_endpointId_fkey"
  FOREIGN KEY ("endpointId") REFERENCES "actuate_webhook_endpoints"("id")
  ON DELETE CASCADE ON UPDATE CASCADE;
