-- CreateEnum
CREATE TYPE "ModulePlanKey" AS ENUM ('PLAN_2_4', 'PLAN_5_7', 'PLAN_8_10');

-- CreateEnum
CREATE TYPE "ModulePlanPurchaseStatus" AS ENUM ('PENDING', 'APPROVED', 'REJECTED', 'CANCELLED', 'EXPIRED');

-- CreateTable
CREATE TABLE "ModulePlanPurchase" (
    "id" TEXT NOT NULL,
    "userId" TEXT NOT NULL,
    "planKey" "ModulePlanKey" NOT NULL,
    "status" "ModulePlanPurchaseStatus" NOT NULL DEFAULT 'PENDING',
    "externalReference" TEXT NOT NULL,
    "mercadoPreferenceId" TEXT,
    "mercadoPaymentId" TEXT,
    "mercadoOrderId" TEXT,
    "checkoutUrl" TEXT,
    "amount" DECIMAL(14,2) NOT NULL,
    "currency" TEXT NOT NULL DEFAULT 'MXN',
    "requestJson" JSONB,
    "responseJson" JSONB,
    "approvedAt" TIMESTAMP(3),
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

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

-- CreateTable
CREATE TABLE "ModulePlanSubscription" (
    "id" TEXT NOT NULL,
    "userId" TEXT NOT NULL,
    "planKey" "ModulePlanKey" NOT NULL,
    "sourcePurchaseId" TEXT,
    "isActive" BOOLEAN NOT NULL DEFAULT true,
    "startsAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "expiresAt" TIMESTAMP(3),
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

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

-- CreateIndex
CREATE UNIQUE INDEX "ModulePlanPurchase_externalReference_key" ON "ModulePlanPurchase"("externalReference");

-- CreateIndex
CREATE INDEX "ModulePlanPurchase_userId_planKey_createdAt_idx" ON "ModulePlanPurchase"("userId", "planKey", "createdAt");

-- CreateIndex
CREATE INDEX "ModulePlanPurchase_status_updatedAt_idx" ON "ModulePlanPurchase"("status", "updatedAt");

-- CreateIndex
CREATE INDEX "ModulePlanPurchase_mercadoPaymentId_idx" ON "ModulePlanPurchase"("mercadoPaymentId");

-- CreateIndex
CREATE UNIQUE INDEX "ModulePlanSubscription_userId_planKey_key" ON "ModulePlanSubscription"("userId", "planKey");

-- CreateIndex
CREATE INDEX "ModulePlanSubscription_userId_isActive_expiresAt_idx" ON "ModulePlanSubscription"("userId", "isActive", "expiresAt");

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

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

-- AddForeignKey
ALTER TABLE "ModulePlanSubscription" ADD CONSTRAINT "ModulePlanSubscription_sourcePurchaseId_fkey" FOREIGN KEY ("sourcePurchaseId") REFERENCES "ModulePlanPurchase"("id") ON DELETE SET NULL ON UPDATE CASCADE;
