-- CreateEnum
CREATE TYPE "RuleIntent" AS ENUM ('POSITIVE', 'NEGATIVE');
CREATE TYPE "ForwardFormat" AS ENUM ('THREADED', 'DIGEST', 'SUMMARY');
CREATE TYPE "ForwardFrequency" AS ENUM ('INSTANT', 'FIVE_MIN', 'FIFTEEN_MIN', 'ONE_HOUR', 'ONE_DAY', 'SEVEN_DAYS');
CREATE TYPE "ApprovalMode" AS ENUM ('MANUAL', 'AUTO');

-- AlterEnum: Add INTEREST to RuleMatchType
ALTER TYPE "RuleMatchType" ADD VALUE IF NOT EXISTS 'INTEREST';

-- AlterTable: TenantRule - add ruleIntent
ALTER TABLE "TenantRule" ADD COLUMN IF NOT EXISTS "ruleIntent" "RuleIntent" NOT NULL DEFAULT 'POSITIVE';

-- AlterTable: SyncRoute - add new columns (updatedAt with default NOW() for existing rows)
ALTER TABLE "SyncRoute"
  ADD COLUMN IF NOT EXISTS "forwardFormat"  "ForwardFormat"    NOT NULL DEFAULT 'THREADED',
  ADD COLUMN IF NOT EXISTS "withAttachment" BOOLEAN            NOT NULL DEFAULT true,
  ADD COLUMN IF NOT EXISTS "frequency"      "ForwardFrequency" NOT NULL DEFAULT 'INSTANT',
  ADD COLUMN IF NOT EXISTS "approvalMode"   "ApprovalMode"     NOT NULL DEFAULT 'MANUAL',
  ADD COLUMN IF NOT EXISTS "updatedAt"      TIMESTAMP(3)       NOT NULL DEFAULT NOW();

-- CreateTable: SyncRouteRuleMap
CREATE TABLE IF NOT EXISTS "SyncRouteRuleMap" (
    "id"           TEXT         NOT NULL,
    "syncRouteId"  TEXT         NOT NULL,
    "tenantRuleId" TEXT         NOT NULL,
    "createdAt"    TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    CONSTRAINT "SyncRouteRuleMap_pkey" PRIMARY KEY ("id")
);

-- CreateIndex
CREATE UNIQUE INDEX IF NOT EXISTS "SyncRouteRuleMap_syncRouteId_tenantRuleId_key"
    ON "SyncRouteRuleMap"("syncRouteId", "tenantRuleId");
CREATE INDEX IF NOT EXISTS "SyncRouteRuleMap_syncRouteId_idx"
    ON "SyncRouteRuleMap"("syncRouteId");
CREATE INDEX IF NOT EXISTS "SyncRouteRuleMap_tenantRuleId_idx"
    ON "SyncRouteRuleMap"("tenantRuleId");

-- AddForeignKey
ALTER TABLE "SyncRouteRuleMap"
    ADD CONSTRAINT "SyncRouteRuleMap_syncRouteId_fkey"
    FOREIGN KEY ("syncRouteId") REFERENCES "SyncRoute"("id") ON DELETE CASCADE ON UPDATE CASCADE;

ALTER TABLE "SyncRouteRuleMap"
    ADD CONSTRAINT "SyncRouteRuleMap_tenantRuleId_fkey"
    FOREIGN KEY ("tenantRuleId") REFERENCES "TenantRule"("id") ON DELETE CASCADE ON UPDATE CASCADE;
