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";
import { emitServerEvent } from "@/lib/events/emitter";

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

export const migrateBadgeProgress = createServerFn()
  .middleware([superTokensAdminFunctionMiddleware])
  .handler(async () =>
    toServerResult(async () => {
      const result = await pbAdmin.migrateBadgeProgress();
      emitServerEvent({ type: "badge" });
      return result;
    })
  );

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()
  .validator(z.object({
    playerId: z.string(),
    badgeId: z.string(),
  }))
  .middleware([superTokensAdminFunctionMiddleware])
  .handler(async ({ data }) =>
    toServerResult(async () => {
      const result = await pbAdmin.awardManualBadge(data.playerId, data.badgeId);
      emitServerEvent({ type: "badge", playerId: data.playerId });
      return result;
    })
  );
