ALTER TABLE "ReferralLink"
ADD COLUMN "createdById" TEXT;

ALTER TABLE "ReferralLink"
ADD COLUMN "bonusPercent" DECIMAL(5,2);

UPDATE "ReferralLink"
SET
  "createdById" = "referrerId",
  "bonusPercent" = 0;

ALTER TABLE "ReferralLink"
ALTER COLUMN "createdById" SET NOT NULL;

ALTER TABLE "ReferralLink"
ALTER COLUMN "bonusPercent" SET NOT NULL;

ALTER TABLE "ReferralLink"
ADD CONSTRAINT "ReferralLink_createdById_fkey"
FOREIGN KEY ("createdById") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

CREATE INDEX "ReferralLink_referrerId_idx" ON "ReferralLink"("referrerId");

CREATE INDEX "ReferralLink_refereeId_idx" ON "ReferralLink"("refereeId");

ALTER TABLE "BonusTransaction"
ADD COLUMN "referralLinkId" TEXT;

ALTER TABLE "BonusTransaction"
ADD CONSTRAINT "BonusTransaction_referralLinkId_fkey"
FOREIGN KEY ("referralLinkId") REFERENCES "ReferralLink"("id") ON DELETE SET NULL ON UPDATE CASCADE;

CREATE UNIQUE INDEX "BonusTransaction_orderId_referralLinkId_key"
ON "BonusTransaction"("orderId", "referralLinkId");
