-- CreateEnum
CREATE TYPE "CrmWebhookEventStatus" AS ENUM ('PENDING', 'PROCESSING', 'PROCESSED', 'FAILED');

-- AlterTable
ALTER TABLE "Conversation"
ADD COLUMN "okoCrmClientId" TEXT,
ADD COLUMN "okoCrmContactId" TEXT,
ADD COLUMN "okoCrmContactMessengerId" TEXT,
ADD COLUMN "okoCrmSettingId" TEXT,
ADD COLUMN "okoCrmAttachedAt" TIMESTAMP(3);

-- CreateTable
CREATE TABLE "CrmWebhookEvent" (
    "id" TEXT NOT NULL,
    "dedupeKey" TEXT NOT NULL,
    "provider" TEXT NOT NULL DEFAULT 'okocrm',
    "eventType" TEXT NOT NULL,
    "providerMessageId" TEXT,
    "clientId" TEXT,
    "contactMessengerId" TEXT,
    "settingId" TEXT,
    "telegramUserId" TEXT,
    "conversationId" TEXT,
    "payload" JSONB NOT NULL,
    "status" "CrmWebhookEventStatus" NOT NULL DEFAULT 'PENDING',
    "attempts" INTEGER NOT NULL DEFAULT 0,
    "nextAttemptAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "lastError" TEXT,
    "receivedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "processedAt" TIMESTAMP(3),

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

-- CreateIndex
CREATE UNIQUE INDEX "Conversation_okoCrmClientId_key" ON "Conversation"("okoCrmClientId");

-- CreateIndex
CREATE UNIQUE INDEX "Conversation_okoCrmContactMessengerId_key" ON "Conversation"("okoCrmContactMessengerId");

-- CreateIndex
CREATE INDEX "Conversation_okoCrmContactId_idx" ON "Conversation"("okoCrmContactId");

-- CreateIndex
CREATE UNIQUE INDEX "CrmWebhookEvent_dedupeKey_key" ON "CrmWebhookEvent"("dedupeKey");

-- CreateIndex
CREATE INDEX "CrmWebhookEvent_status_nextAttemptAt_idx" ON "CrmWebhookEvent"("status", "nextAttemptAt");

-- CreateIndex
CREATE INDEX "CrmWebhookEvent_clientId_idx" ON "CrmWebhookEvent"("clientId");

-- CreateIndex
CREATE INDEX "CrmWebhookEvent_contactMessengerId_idx" ON "CrmWebhookEvent"("contactMessengerId");

-- CreateIndex
CREATE INDEX "CrmWebhookEvent_telegramUserId_idx" ON "CrmWebhookEvent"("telegramUserId");

-- AddForeignKey
ALTER TABLE "CrmWebhookEvent" ADD CONSTRAINT "CrmWebhookEvent_conversationId_fkey" FOREIGN KEY ("conversationId") REFERENCES "Conversation"("id") ON DELETE SET NULL ON UPDATE CASCADE;
