-- CreateTable
CREATE TABLE "IiosInboundRawEvent" (
    "id" TEXT NOT NULL,
    "channelType" TEXT NOT NULL,
    "externalEventId" TEXT,
    "signatureStatus" TEXT NOT NULL,
    "status" TEXT NOT NULL DEFAULT 'RECEIVED',
    "headers" JSONB,
    "payload" JSONB NOT NULL,
    "traceId" TEXT,
    "interactionId" TEXT,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

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

-- CreateTable
CREATE TABLE "IiosOutboundCommand" (
    "id" TEXT NOT NULL,
    "channelType" TEXT NOT NULL,
    "target" TEXT NOT NULL,
    "payload" JSONB NOT NULL,
    "status" TEXT NOT NULL DEFAULT 'PENDING',
    "idempotencyKey" TEXT NOT NULL,
    "providerRef" TEXT,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

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

-- CreateTable
CREATE TABLE "IiosDeliveryAttempt" (
    "id" TEXT NOT NULL,
    "commandId" TEXT NOT NULL,
    "attemptNo" INTEGER NOT NULL,
    "status" TEXT NOT NULL,
    "providerRef" TEXT,
    "latencyMs" INTEGER,
    "errorCode" TEXT,
    "at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

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

-- CreateTable
CREATE TABLE "IiosRateLimitBucket" (
    "channelType" TEXT NOT NULL,
    "bucketKey" TEXT NOT NULL,
    "windowStart" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "count" INTEGER NOT NULL DEFAULT 0,
    "resetAt" TIMESTAMP(3) NOT NULL,

    CONSTRAINT "IiosRateLimitBucket_pkey" PRIMARY KEY ("channelType","bucketKey")
);

-- CreateIndex
CREATE INDEX "IiosInboundRawEvent_status_idx" ON "IiosInboundRawEvent"("status");

-- CreateIndex
CREATE UNIQUE INDEX "IiosInboundRawEvent_channelType_externalEventId_key" ON "IiosInboundRawEvent"("channelType", "externalEventId");

-- CreateIndex
CREATE UNIQUE INDEX "IiosOutboundCommand_idempotencyKey_key" ON "IiosOutboundCommand"("idempotencyKey");

-- CreateIndex
CREATE INDEX "IiosOutboundCommand_channelType_status_idx" ON "IiosOutboundCommand"("channelType", "status");

-- CreateIndex
CREATE INDEX "IiosDeliveryAttempt_commandId_idx" ON "IiosDeliveryAttempt"("commandId");

-- AddForeignKey
ALTER TABLE "IiosDeliveryAttempt" ADD CONSTRAINT "IiosDeliveryAttempt_commandId_fkey" FOREIGN KEY ("commandId") REFERENCES "IiosOutboundCommand"("id") ON DELETE CASCADE ON UPDATE CASCADE;
