/*
  Warnings:

  - You are about to drop the column `mpesaRef` on the `subscriptions` table. All the data in the column will be lost.
  - A unique constraint covering the columns `[customerRef]` on the table `users` will be added. If there are existing duplicate values, this will fail.

*/
-- AlterTable
ALTER TABLE "subscriptions" DROP COLUMN "mpesaRef";

-- AlterTable
ALTER TABLE "users" ADD COLUMN     "customerRef" TEXT;

-- CreateTable
CREATE TABLE "transactions" (
    "id" TEXT NOT NULL,
    "userId" TEXT NOT NULL,
    "subscriptionId" TEXT NOT NULL,
    "mpesaRef" TEXT NOT NULL,
    "amount" DOUBLE PRECISION NOT NULL,
    "currency" TEXT NOT NULL DEFAULT 'TZS',
    "type" TEXT NOT NULL,
    "status" TEXT NOT NULL DEFAULT 'pending',
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "verifiedAt" TIMESTAMP(3),
    "verifiedBy" TEXT,

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

-- CreateIndex
CREATE UNIQUE INDEX "users_customerRef_key" ON "users"("customerRef");

-- AddForeignKey
ALTER TABLE "transactions" ADD CONSTRAINT "transactions_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "transactions" ADD CONSTRAINT "transactions_subscriptionId_fkey" FOREIGN KEY ("subscriptionId") REFERENCES "subscriptions"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- Populate existing users with unique customer refs
UPDATE "users" SET "customerRef" = 'IQRA-' || SUBSTRING(gen_random_uuid()::text FROM 1 FOR 8) WHERE "customerRef" IS NULL;

-- Make customerRef NOT NULL now that all rows have values
ALTER TABLE "users" ALTER COLUMN "customerRef" SET NOT NULL;