import PocketBase from "pocketbase";
import { transformReaction } from "../util/transform-types";

export const createReactionsService = (pb: PocketBase) => ({
  async getReactionsForMatch(matchId: string) {
    const reactions =  await pb.collection('reactions').getFullList({
      filter: `match="${matchId}"`,
      expand: 'player',
    });
    return reactions.map(transformReaction)
  },

  async getUserReaction(matchId: string, userId: string, emoji: string) {
    try {
      return await pb.collection('reactions').getFirstListItem(`match="${matchId}" && player="${userId}" && emoji="${emoji}"`);
    } catch (error) {
      return;
    }
  },

  async createReaction(matchId: string, userId: string, emoji: string) {
    const reaction =  await pb.collection('reactions').create({
      match: matchId,
      player: userId,
      emoji: emoji,
    }, {
      expand: 'player'
    });
    return transformReaction(reaction)
  },

  async deleteReaction(reactionId: string) {
    return await pb.collection('reactions').delete(reactionId);
  },
});