-- AlterTable
ALTER TABLE "sales" ADD COLUMN     "loyaltyPointsEarned" INTEGER NOT NULL DEFAULT 0,
ADD COLUMN     "loyaltyPointsRedeemed" INTEGER NOT NULL DEFAULT 0;

-- CreateTable
CREATE TABLE "loyalty_point_grants" (
    "id" TEXT NOT NULL,
    "shopId" TEXT NOT NULL,
    "customerId" TEXT NOT NULL,
    "earnedSaleId" TEXT,
    "pointsGranted" INTEGER NOT NULL,
    "pointsRemaining" INTEGER NOT NULL,
    "expiresAt" TIMESTAMP(3) NOT NULL,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

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

-- CreateTable
CREATE TABLE "loyalty_point_usages" (
    "id" TEXT NOT NULL,
    "grantId" TEXT NOT NULL,
    "saleId" TEXT NOT NULL,
    "pointsUsed" INTEGER NOT NULL,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

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

-- CreateIndex
CREATE UNIQUE INDEX "loyalty_point_grants_earnedSaleId_key" ON "loyalty_point_grants"("earnedSaleId");

-- CreateIndex
CREATE INDEX "loyalty_point_grants_shopId_customerId_expiresAt_idx" ON "loyalty_point_grants"("shopId", "customerId", "expiresAt");

-- CreateIndex
CREATE INDEX "loyalty_point_grants_customerId_expiresAt_idx" ON "loyalty_point_grants"("customerId", "expiresAt");

-- CreateIndex
CREATE INDEX "loyalty_point_usages_saleId_idx" ON "loyalty_point_usages"("saleId");

-- CreateIndex
CREATE INDEX "loyalty_point_usages_grantId_idx" ON "loyalty_point_usages"("grantId");

-- AddForeignKey
ALTER TABLE "loyalty_point_grants" ADD CONSTRAINT "loyalty_point_grants_shopId_fkey" FOREIGN KEY ("shopId") REFERENCES "shops"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "loyalty_point_grants" ADD CONSTRAINT "loyalty_point_grants_customerId_fkey" FOREIGN KEY ("customerId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "loyalty_point_grants" ADD CONSTRAINT "loyalty_point_grants_earnedSaleId_fkey" FOREIGN KEY ("earnedSaleId") REFERENCES "sales"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "loyalty_point_usages" ADD CONSTRAINT "loyalty_point_usages_grantId_fkey" FOREIGN KEY ("grantId") REFERENCES "loyalty_point_grants"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "loyalty_point_usages" ADD CONSTRAINT "loyalty_point_usages_saleId_fkey" FOREIGN KEY ("saleId") REFERENCES "sales"("id") ON DELETE CASCADE ON UPDATE CASCADE;
