import { superTokensFunctionMiddleware, 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 { teamInputSchema, teamUpdateSchema } from "./types";
import { logger } from "@/lib/logger";
import { Match } from "../matches/types";
import { serverFnLoggingMiddleware } from "@/utils/activities";
import { emitServerEvent } from "@/lib/events/emitter";


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

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

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

export const createTeam = createServerFn()
  .validator(teamInputSchema)
  .middleware([superTokensFunctionMiddleware, serverFnLoggingMiddleware])
  .handler(async ({ data, context }) => 
    toServerResult(async () => {
      const userId = context.userAuthId;
      const isAdmin = context.roles.includes("Admin");
      
      //if (!isAdmin && !data.players.includes(userId)) {
      //  throw new Error("You can only create teams that include yourself as a player");
      //}

      logger.info("Creating team", { name: data.name, userId, isAdmin });
      const team = await pbAdmin.createTeam(data);
      emitServerEvent({ type: "team", teamId: team?.id });
      return team;
    })
  );

export const updateTeam = createServerFn()
  .validator(z.object({
    id: z.string(),
    updates: teamUpdateSchema
  }))
  .middleware([superTokensFunctionMiddleware, serverFnLoggingMiddleware])
  .handler(async ({ data: { id, updates }, context }) =>
    toServerResult(async () => {
      const userId = context.userAuthId;
      const isAdmin = context.roles.includes("Admin");

      const team = await pbAdmin.getTeam(id);
      if (!team) {
        throw new Error("Team not found");
      }

      //const isPlayerOnTeam = team.players.some(player => player.id === userId);
      //if (!isAdmin && !isPlayerOnTeam) {
      //  throw new Error("You can only update teams that you are a member of");
      // }

      logger.info("Updating team", { teamId: id, userId, isAdmin });
      const updated = await pbAdmin.updateTeam(id, updates);
      emitServerEvent({ type: "team", teamId: id });
      return updated;
    })
  );

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

export const getTeamMatches = createServerFn()
  .validator(z.string())
  .middleware([superTokensFunctionMiddleware])
  .handler(async ({ data }) =>
    toServerResult<Match[]>(async () => await pbAdmin.getTeamMatches(data))
  );
