-- CreateEnum
CREATE TYPE "IiosRouteMode" AS ENUM ('MANUAL', 'AUTOMATIC', 'HYBRID', 'SIMULATION_ONLY');

-- CreateEnum
CREATE TYPE "IiosOutputFormat" AS ENUM ('FORWARD', 'THREADED', 'DIGEST', 'SUMMARY', 'TRANSCRIPT');

-- CreateEnum
CREATE TYPE "IiosRouteDecisionState" AS ENUM ('ALLOW', 'DENY', 'REVIEW', 'SUPPRESS', 'SIMULATED');

-- CreateTable
CREATE TABLE "IiosRouteBinding" (
    "id" TEXT NOT NULL,
    "scopeId" TEXT NOT NULL,
    "originChannelType" TEXT NOT NULL,
    "originRef" TEXT,
    "destinationChannelType" TEXT NOT NULL,
    "destinationRef" TEXT,
    "restrictionProfile" TEXT,
    "mode" "IiosRouteMode" NOT NULL DEFAULT 'SIMULATION_ONLY',
    "outputFormat" "IiosOutputFormat" NOT NULL DEFAULT 'FORWARD',
    "frequency" TEXT NOT NULL DEFAULT 'IMMEDIATE',
    "includeAttachments" BOOLEAN NOT NULL DEFAULT false,
    "requiresReview" BOOLEAN NOT NULL DEFAULT true,
    "rulepackVersion" TEXT NOT NULL DEFAULT 'v1',
    "enabled" BOOLEAN NOT NULL DEFAULT false,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

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

-- CreateTable
CREATE TABLE "IiosRouteDecision" (
    "id" TEXT NOT NULL,
    "interactionId" TEXT NOT NULL,
    "routeBindingId" TEXT NOT NULL,
    "decisionState" "IiosRouteDecisionState" NOT NULL,
    "reasonCodes" TEXT[],
    "previewPayload" JSONB NOT NULL,
    "outputFormat" "IiosOutputFormat" NOT NULL,
    "rulepackVersion" TEXT NOT NULL,
    "simulationId" TEXT,
    "decidedByActorId" TEXT,
    "executed" BOOLEAN NOT NULL DEFAULT false,
    "executedCommandId" TEXT,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

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

-- CreateTable
CREATE TABLE "IiosModerationFlag" (
    "id" TEXT NOT NULL,
    "interactionId" TEXT NOT NULL,
    "flagType" TEXT NOT NULL,
    "severity" TEXT NOT NULL DEFAULT 'LOW',
    "proposedBy" TEXT NOT NULL DEFAULT 'RULE',
    "confidence" DOUBLE PRECISION,
    "explanation" TEXT,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "resolvedAt" TIMESTAMP(3),

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

-- CreateIndex
CREATE INDEX "IiosRouteBinding_scopeId_originChannelType_idx" ON "IiosRouteBinding"("scopeId", "originChannelType");

-- CreateIndex
CREATE INDEX "IiosRouteDecision_decisionState_idx" ON "IiosRouteDecision"("decisionState");

-- CreateIndex
CREATE UNIQUE INDEX "IiosRouteDecision_interactionId_routeBindingId_key" ON "IiosRouteDecision"("interactionId", "routeBindingId");

-- CreateIndex
CREATE INDEX "IiosModerationFlag_interactionId_idx" ON "IiosModerationFlag"("interactionId");

-- AddForeignKey
ALTER TABLE "IiosRouteDecision" ADD CONSTRAINT "IiosRouteDecision_routeBindingId_fkey" FOREIGN KEY ("routeBindingId") REFERENCES "IiosRouteBinding"("id") ON DELETE CASCADE ON UPDATE CASCADE;
