import { toServerResult } from "@/lib/tanstack-query/utils/to-server-result";
import { superTokensAdminFunctionMiddleware, superTokensFunctionMiddleware } from "@/utils/supertokens";
import { createServerFn } from "@tanstack/react-start";
import { pbAdmin } from "@/lib/pocketbase/client";
import { z } from "zod";

export const getPlayerBadges = createServerFn()
  .inputValidator(z.string())
  .middleware([superTokensFunctionMiddleware])
  .handler(async ({ data: playerId }) =>
    toServerResult(() => pbAdmin.getPlayerBadgeProgress(playerId))
  );

export const migrateBadgeProgress = createServerFn()
  .middleware([superTokensAdminFunctionMiddleware])
  .handler(async () =>
    toServerResult(() => pbAdmin.migrateBadgeProgress())
  );

export const getAllBadges = createServerFn()
  .middleware([superTokensFunctionMiddleware])
  .handler(async () =>
    toServerResult(() => pbAdmin.listBadges())
  );

export const getAllEarnedBadges = createServerFn()
  .middleware([superTokensFunctionMiddleware])
  .handler(async () => toServerResult(() => pbAdmin.listEarnedBadges()));

export const awardManualBadge = createServerFn()
  .inputValidator(z.object({
    playerId: z.string(),
    badgeId: z.string(),
  }))
  .middleware([superTokensAdminFunctionMiddleware])
  .handler(async ({ data }) =>
    toServerResult(() => pbAdmin.awardManualBadge(data.playerId, data.badgeId))
  );
