-- Make email/password optional for phone-OTP users.
ALTER TABLE "User" ALTER COLUMN "name" DROP NOT NULL;
ALTER TABLE "User" ALTER COLUMN "email" DROP NOT NULL;
ALTER TABLE "User" ALTER COLUMN "passwordHash" DROP NOT NULL;

-- Re-key User.id from TEXT (cuid) to INTEGER autoincrement while preserving Session links.
ALTER TABLE "Session" DROP CONSTRAINT "Session_userId_fkey";
ALTER TABLE "User" ADD COLUMN "new_id" SERIAL;
ALTER TABLE "Session" ADD COLUMN "new_user_id" INTEGER;

UPDATE "Session" s
SET "new_user_id" = u."new_id"
FROM "User" u
WHERE s."userId" = u."id";

ALTER TABLE "User" DROP CONSTRAINT "User_pkey";
ALTER TABLE "User" DROP COLUMN "id";
ALTER TABLE "User" RENAME COLUMN "new_id" TO "id";
ALTER TABLE "User" ADD CONSTRAINT "User_pkey" PRIMARY KEY ("id");

ALTER TABLE "Session" DROP COLUMN "userId";
ALTER TABLE "Session" RENAME COLUMN "new_user_id" TO "userId";
ALTER TABLE "Session" ALTER COLUMN "userId" SET NOT NULL;
ALTER TABLE "Session" ADD CONSTRAINT "Session_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- Ensure phone can be used as the login identifier.
CREATE UNIQUE INDEX IF NOT EXISTS "User_phone_key" ON "User"("phone");
