import { logger } from "@/lib/logger";
import PocketBase from "pocketbase";
import { Group } from "@/features/tournaments/types";

export interface GroupInput {
  tournament: string;
  name: string;
  order: number;
  teams: string[];
}

export function createGroupsService(pb: PocketBase) {
  return {
    async createGroup(data: GroupInput): Promise<Group> {
      logger.info("PocketBase | Creating group", data);
      const result = await pb.collection("groups").create(data);
      return result as unknown as Group;
    },

    async getGroupsByTournament(tournamentId: string): Promise<Group[]> {
      logger.info("PocketBase | Getting groups for tournament", { tournamentId });
      const result = await pb.collection("groups").getFullList({
        filter: `tournament = "${tournamentId}"`,
        sort: "order",
        expand: "teams,teams.players"
      });
      return result as unknown as Group[];
    },

    async deleteGroup(groupId: string): Promise<void> {
      logger.info("PocketBase | Deleting group", { groupId });
      await pb.collection("groups").delete(groupId);
    },

    async deleteGroupsByTournament(tournamentId: string): Promise<void> {
      logger.info("PocketBase | Deleting all groups for tournament", { tournamentId });
      const groups = await pb.collection("groups").getFullList({
        filter: `tournament = "${tournamentId}"`,
        fields: "id",
      });

      await Promise.all(
        groups.map((group) => pb.collection("groups").delete(group.id))
      );
    },

    async getGroup(groupId: string): Promise<Group> {
      logger.info("PocketBase | Getting group", { groupId });
      const result = await pb.collection("groups").getOne(groupId, {
        expand: "teams,teams.players"
      });
      return result as unknown as Group;
    }
  };
}
