-- CreateEnum
CREATE TYPE "IiosReceiptKind" AS ENUM ('DELIVERED', 'READ', 'ACKED', 'FAILED', 'SUPPRESSED', 'RATE_LIMITED');

-- CreateTable
CREATE TABLE "IiosMessageReceipt" (
    "id" TEXT NOT NULL,
    "interactionId" TEXT NOT NULL,
    "actorId" TEXT,
    "receiptKind" "IiosReceiptKind" NOT NULL,
    "occurredAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "providerReceiptRef" TEXT,
    "metadata" JSONB,

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

-- CreateTable
CREATE TABLE "IiosUnreadCounter" (
    "threadId" TEXT NOT NULL,
    "actorId" TEXT NOT NULL,
    "unreadCount" INTEGER NOT NULL DEFAULT 0,
    "lastReadInteractionId" TEXT,
    "updatedAt" TIMESTAMP(3) NOT NULL,

    CONSTRAINT "IiosUnreadCounter_pkey" PRIMARY KEY ("threadId","actorId")
);

-- CreateIndex
CREATE INDEX "IiosMessageReceipt_interactionId_idx" ON "IiosMessageReceipt"("interactionId");

-- CreateIndex
CREATE UNIQUE INDEX "IiosMessageReceipt_interactionId_actorId_receiptKind_key" ON "IiosMessageReceipt"("interactionId", "actorId", "receiptKind");

-- AddForeignKey
ALTER TABLE "IiosMessageReceipt" ADD CONSTRAINT "IiosMessageReceipt_interactionId_fkey" FOREIGN KEY ("interactionId") REFERENCES "IiosInteraction"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "IiosMessageReceipt" ADD CONSTRAINT "IiosMessageReceipt_actorId_fkey" FOREIGN KEY ("actorId") REFERENCES "IiosActorRef"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "IiosUnreadCounter" ADD CONSTRAINT "IiosUnreadCounter_threadId_fkey" FOREIGN KEY ("threadId") REFERENCES "IiosThread"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "IiosUnreadCounter" ADD CONSTRAINT "IiosUnreadCounter_actorId_fkey" FOREIGN KEY ("actorId") REFERENCES "IiosActorRef"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
