-- CreateEnum
CREATE TYPE "ConflictReviewStatus" AS ENUM ('PENDING', 'POTENTIAL_MATCH', 'CLEARED', 'WAIVED', 'BLOCKED');

-- CreateEnum
CREATE TYPE "EngagementStatus" AS ENUM ('DRAFT', 'SENT', 'VIEWED', 'SIGNED', 'DECLINED', 'EXPIRED', 'VOIDED');

-- CreateTable
CREATE TABLE "lead_conflict_reviews" (
    "id" TEXT NOT NULL,
    "leadId" TEXT NOT NULL,
    "status" "ConflictReviewStatus" NOT NULL DEFAULT 'PENDING',
    "searchedTerms" JSONB NOT NULL,
    "matches" JSONB NOT NULL,
    "reviewerId" TEXT,
    "reviewedAt" TIMESTAMP(3),
    "decisionNotes" TEXT,
    "waiverReference" TEXT,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

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

-- CreateTable
CREATE TABLE "lead_engagements" (
    "id" TEXT NOT NULL,
    "leadId" TEXT NOT NULL,
    "status" "EngagementStatus" NOT NULL DEFAULT 'DRAFT',
    "templateName" TEXT NOT NULL,
    "templateVersion" TEXT NOT NULL,
    "createdBy" TEXT NOT NULL,
    "sentAt" TIMESTAMP(3),
    "viewedAt" TIMESTAMP(3),
    "signedAt" TIMESTAMP(3),
    "signedByName" TEXT,
    "declinedAt" TIMESTAMP(3),
    "expiresAt" TIMESTAMP(3),
    "externalReference" TEXT,
    "notes" TEXT,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

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

-- CreateIndex
CREATE INDEX "lead_conflict_reviews_leadId_createdAt_idx" ON "lead_conflict_reviews"("leadId", "createdAt");

-- CreateIndex
CREATE INDEX "lead_conflict_reviews_status_idx" ON "lead_conflict_reviews"("status");

-- CreateIndex
CREATE INDEX "lead_engagements_leadId_status_idx" ON "lead_engagements"("leadId", "status");

-- AddForeignKey
ALTER TABLE "lead_conflict_reviews" ADD CONSTRAINT "lead_conflict_reviews_leadId_fkey" FOREIGN KEY ("leadId") REFERENCES "leads"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "lead_conflict_reviews" ADD CONSTRAINT "lead_conflict_reviews_reviewerId_fkey" FOREIGN KEY ("reviewerId") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "lead_engagements" ADD CONSTRAINT "lead_engagements_leadId_fkey" FOREIGN KEY ("leadId") REFERENCES "leads"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "lead_engagements" ADD CONSTRAINT "lead_engagements_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "users"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
