import PocketBase from "pocketbase";
import { PicksMap, Prediction } from "@/features/predictions/types";
import { transformPrediction } from "../util/transform-types";

export function createPredictionsService(pb: PocketBase) {
  return {
    async getPrediction(
      tournamentId: string,
      playerId: string
    ): Promise<Prediction | null> {
      try {
        const record = await pb
          .collection("predictions")
          .getFirstListItem(
            `tournament="${tournamentId}" && player="${playerId}"`,
            { expand: "player" }
          );
        return transformPrediction(record);
      } catch (error) {
        return null;
      }
    },

    async getPredictionsForTournament(
      tournamentId: string
    ): Promise<Prediction[]> {
      const records = await pb.collection("predictions").getFullList({
        filter: `tournament="${tournamentId}"`,
        expand: "player",
        sort: "updated",
      });
      return records.map(transformPrediction);
    },

    async upsertPrediction(
      tournamentId: string,
      playerId: string,
      picks: PicksMap
    ): Promise<Prediction> {
      const existing = await this.getPrediction(tournamentId, playerId);

      const record = existing
        ? await pb
            .collection("predictions")
            .update(existing.id, { picks }, { expand: "player" })
        : await pb.collection("predictions").create(
            {
              tournament: tournamentId,
              player: playerId,
              picks,
            },
            { expand: "player" }
          );

      return transformPrediction(record);
    },

    async deletePredictionsForTournament(tournamentId: string): Promise<void> {
      const records = await pb.collection("predictions").getFullList({
        filter: `tournament="${tournamentId}"`,
        fields: "id",
      });
      for (const record of records) {
        await pb.collection("predictions").delete(record.id);
      }
    },
  };
}
