import { superTokensAdminFunctionMiddleware } from "@/utils/supertokens";
import { createServerFn } from "@tanstack/react-start";
import { pbAdmin } from "@/lib/pocketbase/client";
import { z } from "zod";
import { toServerResult } from "@/lib/tanstack-query/utils/to-server-result";
import { transformActivity } from "@/lib/pocketbase/util/transform-types";
import { Activity, ActivityListResult, ActivitySearchParams } from "./types";

const activitySearchParamsSchema = z.object({
  page: z.number().optional(),
  perPage: z.number().optional(),
  name: z.string().optional(),
  player: z.string().optional(),
  success: z.boolean().optional(),
  sortBy: z.string().optional(),
});

export const searchActivities = createServerFn()
  .validator(activitySearchParamsSchema)
  .middleware([superTokensAdminFunctionMiddleware])
  .handler(async ({ data }) =>
    toServerResult<ActivityListResult>(async () => {
      const result = await pbAdmin.searchActivities(data);
      return {
        ...result,
        items: result.items.map(transformActivity),
      };
    })
  );
