-- CreateTable
CREATE TABLE "user_invites" (
    "id" BIGSERIAL NOT NULL,
    "code" VARCHAR(16) NOT NULL,
    "sponsor_id" BIGINT NOT NULL,
    "status" VARCHAR(20) NOT NULL DEFAULT 'ACTIVE',
    "register_count" INTEGER NOT NULL DEFAULT 0,
    "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "revoked_at" TIMESTAMP(3),

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

-- CreateIndex
CREATE UNIQUE INDEX "user_invites_code_key" ON "user_invites"("code");
CREATE INDEX "user_invites_sponsor_id_idx" ON "user_invites"("sponsor_id");
CREATE INDEX "user_invites_status_idx" ON "user_invites"("status");
CREATE INDEX "user_invites_created_at_idx" ON "user_invites"("created_at");

-- AddForeignKey
ALTER TABLE "user_invites" ADD CONSTRAINT "user_invites_sponsor_id_fkey" FOREIGN KEY ("sponsor_id") REFERENCES "users"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

-- AlterTable
ALTER TABLE "users" ADD COLUMN "used_invite_id" BIGINT;
CREATE INDEX "users_used_invite_id_idx" ON "users"("used_invite_id");
ALTER TABLE "users" ADD CONSTRAINT "users_used_invite_id_fkey" FOREIGN KEY ("used_invite_id") REFERENCES "user_invites"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- Backfill existing invite codes into history
INSERT INTO "user_invites" ("code", "sponsor_id", "status", "register_count", "created_at")
SELECT u."invite_code", u."id", 'ACTIVE', 0, COALESCE(u."updated_at", u."created_at")
FROM "users" u
WHERE u."invite_code" IS NOT NULL
  AND u."user_type" IN ('ADMIN', 'AGENT')
ON CONFLICT ("code") DO NOTHING;

-- Link players to invite records when possible
UPDATE "users" p
SET "used_invite_id" = ui."id"
FROM "user_invites" ui
WHERE p."invite_sponsor_id" = ui."sponsor_id"
  AND p."user_type" = 'PLAYER'
  AND p."used_invite_id" IS NULL
  AND ui."status" = 'ACTIVE'
  AND ui."code" = (
    SELECT s."invite_code" FROM "users" s WHERE s."id" = p."invite_sponsor_id"
  );

UPDATE "user_invites" ui
SET "register_count" = sub.cnt
FROM (
  SELECT "used_invite_id" AS id, COUNT(*)::int AS cnt
  FROM "users"
  WHERE "used_invite_id" IS NOT NULL
  GROUP BY "used_invite_id"
) sub
WHERE ui."id" = sub.id;
