-- CreateEnum
CREATE TYPE "ContractStatus" AS ENUM ('ACTIVE', 'COMPLETED', 'PAUSED', 'CANCELLED');

-- CreateEnum
CREATE TYPE "ContractDeliverableStatus" AS ENUM ('PENDING', 'DELIVERED', 'APPROVED', 'REJECTED', 'OVERDUE');

-- CreateEnum
CREATE TYPE "ContractPaymentStatus" AS ENUM ('REGISTERED', 'CONFIRMED', 'DISPUTED');

-- CreateEnum
CREATE TYPE "ContractDocumentKind" AS ENUM ('SIGNED_CONTRACT', 'ADDENDUM', 'DELIVERABLE_EVIDENCE', 'PAYMENT_EVIDENCE', 'OTHER');

-- CreateEnum
CREATE TYPE "LegalCaseType" AS ENUM ('CONTRACT_BREACH', 'PAYMENT_RETENTION', 'UNJUST_SANCTION', 'CONTRACT_DISPUTE');

-- CreateEnum
CREATE TYPE "LegalCaseSeverity" AS ENUM ('LOW', 'MEDIUM', 'HIGH');

-- CreateEnum
CREATE TYPE "LegalCaseStatus" AS ENUM ('OPEN', 'IN_PROGRESS', 'ESCALATED', 'RESOLVED', 'CLOSED');

-- CreateEnum
CREATE TYPE "LegalJurisdictionLevel" AS ENUM ('FEDERAL', 'STATE', 'MUNICIPAL');

-- CreateEnum
CREATE TYPE "AuditSimulationStatus" AS ENUM ('DRAFT', 'COMPLETED');

-- CreateEnum
CREATE TYPE "AuditSimulationSectionStatus" AS ENUM ('READY', 'WARNING', 'CRITICAL');

-- CreateTable
CREATE TABLE "ContractRecord" (
    "id" TEXT NOT NULL,
    "userId" TEXT NOT NULL,
    "sourceProposalId" TEXT,
    "title" TEXT NOT NULL,
    "counterpartyEntity" TEXT NOT NULL,
    "contractNumber" TEXT,
    "contractType" TEXT NOT NULL,
    "startDate" TIMESTAMP(3),
    "endDate" TIMESTAMP(3),
    "totalAmount" DECIMAL(14,2),
    "currency" TEXT NOT NULL DEFAULT 'MXN',
    "status" "ContractStatus" NOT NULL DEFAULT 'ACTIVE',
    "description" TEXT NOT NULL DEFAULT '',
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

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

-- CreateTable
CREATE TABLE "ContractDeliverable" (
    "id" TEXT NOT NULL,
    "contractId" TEXT NOT NULL,
    "title" TEXT NOT NULL,
    "dueDate" TIMESTAMP(3),
    "amountLinked" DECIMAL(14,2),
    "status" "ContractDeliverableStatus" NOT NULL DEFAULT 'PENDING',
    "deliveredAt" TIMESTAMP(3),
    "approvedAt" TIMESTAMP(3),
    "notes" TEXT NOT NULL DEFAULT '',
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

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

-- CreateTable
CREATE TABLE "ContractPayment" (
    "id" TEXT NOT NULL,
    "contractId" TEXT NOT NULL,
    "amount" DECIMAL(14,2) NOT NULL,
    "paymentDate" TIMESTAMP(3) NOT NULL,
    "invoiceNumber" TEXT,
    "concept" TEXT NOT NULL DEFAULT '',
    "status" "ContractPaymentStatus" NOT NULL DEFAULT 'REGISTERED',
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

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

-- CreateTable
CREATE TABLE "ContractDocument" (
    "id" TEXT NOT NULL,
    "contractId" TEXT NOT NULL,
    "fileName" TEXT NOT NULL,
    "filePath" TEXT NOT NULL,
    "mimeType" TEXT NOT NULL,
    "sizeBytes" INTEGER NOT NULL,
    "checksumSha256" TEXT,
    "kind" "ContractDocumentKind" NOT NULL DEFAULT 'OTHER',
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

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

-- CreateTable
CREATE TABLE "ContractExtractionHistory" (
    "id" TEXT NOT NULL,
    "contractId" TEXT,
    "userId" TEXT NOT NULL,
    "engine" TEXT NOT NULL,
    "model" TEXT,
    "resultJson" JSONB NOT NULL,
    "warningsJson" JSONB,
    "analyzedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

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

-- CreateTable
CREATE TABLE "LegalCase" (
    "id" TEXT NOT NULL,
    "userId" TEXT NOT NULL,
    "contractId" TEXT,
    "caseType" "LegalCaseType" NOT NULL,
    "severity" "LegalCaseSeverity" NOT NULL,
    "counterparty" TEXT NOT NULL,
    "description" TEXT NOT NULL,
    "amountAtRisk" DECIMAL(14,2),
    "status" "LegalCaseStatus" NOT NULL DEFAULT 'OPEN',
    "openedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "resolvedAt" TIMESTAMP(3),
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

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

-- CreateTable
CREATE TABLE "LegalDiagnosis" (
    "id" TEXT NOT NULL,
    "userId" TEXT NOT NULL,
    "legalCaseId" TEXT,
    "stepIndex" INTEGER NOT NULL DEFAULT 1,
    "totalSteps" INTEGER NOT NULL DEFAULT 4,
    "answersJson" JSONB NOT NULL,
    "recommendedRouteJson" JSONB NOT NULL,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

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

-- CreateTable
CREATE TABLE "LegalEscalationStepLog" (
    "id" TEXT NOT NULL,
    "legalCaseId" TEXT NOT NULL,
    "routeStepKey" TEXT NOT NULL,
    "completedAt" TIMESTAMP(3),
    "notes" TEXT NOT NULL DEFAULT '',
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

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

-- CreateTable
CREATE TABLE "LegalDocument" (
    "id" TEXT NOT NULL,
    "legalCaseId" TEXT,
    "userId" TEXT NOT NULL,
    "templateKey" TEXT,
    "aiGenerated" BOOLEAN NOT NULL DEFAULT false,
    "title" TEXT NOT NULL,
    "content" TEXT NOT NULL,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

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

-- CreateTable
CREATE TABLE "LegalDirectoryEntity" (
    "id" TEXT NOT NULL,
    "jurisdictionLevel" "LegalJurisdictionLevel" NOT NULL,
    "name" TEXT NOT NULL,
    "scopeTagsJson" JSONB NOT NULL,
    "websiteUrl" TEXT,
    "phone" TEXT,
    "email" TEXT,
    "stateCode" TEXT,
    "municipalityCode" TEXT,
    "isActive" BOOLEAN NOT NULL DEFAULT true,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

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

-- CreateTable
CREATE TABLE "AuditSimulation" (
    "id" TEXT NOT NULL,
    "userId" TEXT NOT NULL,
    "name" TEXT NOT NULL,
    "auditType" TEXT NOT NULL,
    "status" "AuditSimulationStatus" NOT NULL DEFAULT 'DRAFT',
    "overallScore" INTEGER,
    "completedAt" TIMESTAMP(3),
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

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

-- CreateTable
CREATE TABLE "AuditSimulationSection" (
    "id" TEXT NOT NULL,
    "simulationId" TEXT NOT NULL,
    "key" TEXT NOT NULL,
    "score" INTEGER,
    "status" "AuditSimulationSectionStatus" NOT NULL DEFAULT 'READY',
    "findingsJson" JSONB,
    "recommendationsJson" JSONB,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

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

-- CreateTable
CREATE TABLE "AuditChecklistResponse" (
    "id" TEXT NOT NULL,
    "simulationId" TEXT NOT NULL,
    "questionKey" TEXT NOT NULL,
    "answer" TEXT NOT NULL,
    "evidenceRefsJson" JSONB,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

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

-- CreateTable
CREATE TABLE "InstitutionalDossierSnapshot" (
    "id" TEXT NOT NULL,
    "userId" TEXT NOT NULL,
    "generatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "payloadJson" JSONB NOT NULL,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

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

-- CreateIndex
CREATE INDEX "ContractRecord_userId_status_endDate_idx" ON "ContractRecord"("userId", "status", "endDate");

-- CreateIndex
CREATE INDEX "ContractRecord_sourceProposalId_idx" ON "ContractRecord"("sourceProposalId");

-- CreateIndex
CREATE INDEX "ContractRecord_updatedAt_idx" ON "ContractRecord"("updatedAt");

-- CreateIndex
CREATE INDEX "ContractDeliverable_contractId_status_dueDate_idx" ON "ContractDeliverable"("contractId", "status", "dueDate");

-- CreateIndex
CREATE INDEX "ContractDeliverable_dueDate_idx" ON "ContractDeliverable"("dueDate");

-- CreateIndex
CREATE INDEX "ContractPayment_contractId_paymentDate_idx" ON "ContractPayment"("contractId", "paymentDate");

-- CreateIndex
CREATE INDEX "ContractPayment_status_paymentDate_idx" ON "ContractPayment"("status", "paymentDate");

-- CreateIndex
CREATE INDEX "ContractDocument_contractId_kind_createdAt_idx" ON "ContractDocument"("contractId", "kind", "createdAt");

-- CreateIndex
CREATE INDEX "ContractExtractionHistory_userId_analyzedAt_idx" ON "ContractExtractionHistory"("userId", "analyzedAt");

-- CreateIndex
CREATE INDEX "ContractExtractionHistory_contractId_analyzedAt_idx" ON "ContractExtractionHistory"("contractId", "analyzedAt");

-- CreateIndex
CREATE INDEX "LegalCase_userId_status_severity_idx" ON "LegalCase"("userId", "status", "severity");

-- CreateIndex
CREATE INDEX "LegalCase_contractId_idx" ON "LegalCase"("contractId");

-- CreateIndex
CREATE INDEX "LegalDiagnosis_userId_updatedAt_idx" ON "LegalDiagnosis"("userId", "updatedAt");

-- CreateIndex
CREATE INDEX "LegalDiagnosis_legalCaseId_idx" ON "LegalDiagnosis"("legalCaseId");

-- CreateIndex
CREATE UNIQUE INDEX "LegalEscalationStepLog_legalCaseId_routeStepKey_key" ON "LegalEscalationStepLog"("legalCaseId", "routeStepKey");

-- CreateIndex
CREATE INDEX "LegalEscalationStepLog_legalCaseId_completedAt_idx" ON "LegalEscalationStepLog"("legalCaseId", "completedAt");

-- CreateIndex
CREATE INDEX "LegalDocument_userId_createdAt_idx" ON "LegalDocument"("userId", "createdAt");

-- CreateIndex
CREATE INDEX "LegalDocument_legalCaseId_createdAt_idx" ON "LegalDocument"("legalCaseId", "createdAt");

-- CreateIndex
CREATE INDEX "LegalDirectoryEntity_jurisdictionLevel_isActive_idx" ON "LegalDirectoryEntity"("jurisdictionLevel", "isActive");

-- CreateIndex
CREATE INDEX "LegalDirectoryEntity_stateCode_municipalityCode_isActive_idx" ON "LegalDirectoryEntity"("stateCode", "municipalityCode", "isActive");

-- CreateIndex
CREATE INDEX "AuditSimulation_userId_status_updatedAt_idx" ON "AuditSimulation"("userId", "status", "updatedAt");

-- CreateIndex
CREATE UNIQUE INDEX "AuditSimulationSection_simulationId_key_key" ON "AuditSimulationSection"("simulationId", "key");

-- CreateIndex
CREATE INDEX "AuditSimulationSection_status_idx" ON "AuditSimulationSection"("status");

-- CreateIndex
CREATE INDEX "AuditChecklistResponse_simulationId_questionKey_idx" ON "AuditChecklistResponse"("simulationId", "questionKey");

-- CreateIndex
CREATE INDEX "InstitutionalDossierSnapshot_userId_generatedAt_idx" ON "InstitutionalDossierSnapshot"("userId", "generatedAt");

-- AddForeignKey
ALTER TABLE "ContractRecord" ADD CONSTRAINT "ContractRecord_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "ContractRecord" ADD CONSTRAINT "ContractRecord_sourceProposalId_fkey" FOREIGN KEY ("sourceProposalId") REFERENCES "Proposal"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "ContractDeliverable" ADD CONSTRAINT "ContractDeliverable_contractId_fkey" FOREIGN KEY ("contractId") REFERENCES "ContractRecord"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "ContractPayment" ADD CONSTRAINT "ContractPayment_contractId_fkey" FOREIGN KEY ("contractId") REFERENCES "ContractRecord"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "ContractDocument" ADD CONSTRAINT "ContractDocument_contractId_fkey" FOREIGN KEY ("contractId") REFERENCES "ContractRecord"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "ContractExtractionHistory" ADD CONSTRAINT "ContractExtractionHistory_contractId_fkey" FOREIGN KEY ("contractId") REFERENCES "ContractRecord"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "ContractExtractionHistory" ADD CONSTRAINT "ContractExtractionHistory_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "LegalCase" ADD CONSTRAINT "LegalCase_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "LegalCase" ADD CONSTRAINT "LegalCase_contractId_fkey" FOREIGN KEY ("contractId") REFERENCES "ContractRecord"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "LegalDiagnosis" ADD CONSTRAINT "LegalDiagnosis_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "LegalDiagnosis" ADD CONSTRAINT "LegalDiagnosis_legalCaseId_fkey" FOREIGN KEY ("legalCaseId") REFERENCES "LegalCase"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "LegalEscalationStepLog" ADD CONSTRAINT "LegalEscalationStepLog_legalCaseId_fkey" FOREIGN KEY ("legalCaseId") REFERENCES "LegalCase"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "LegalDocument" ADD CONSTRAINT "LegalDocument_legalCaseId_fkey" FOREIGN KEY ("legalCaseId") REFERENCES "LegalCase"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "LegalDocument" ADD CONSTRAINT "LegalDocument_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "AuditSimulation" ADD CONSTRAINT "AuditSimulation_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "AuditSimulationSection" ADD CONSTRAINT "AuditSimulationSection_simulationId_fkey" FOREIGN KEY ("simulationId") REFERENCES "AuditSimulation"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "AuditChecklistResponse" ADD CONSTRAINT "AuditChecklistResponse_simulationId_fkey" FOREIGN KEY ("simulationId") REFERENCES "AuditSimulation"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "InstitutionalDossierSnapshot" ADD CONSTRAINT "InstitutionalDossierSnapshot_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
