import PocketBase from "pocketbase";
import { PlayerInfo } from "@/features/players/types";

export interface Activity {
  id: string;
  name: string;
  player?: string | PlayerInfo;
  duration: number;
  success: boolean;
  error?: string;
  arguments?: any;
  user_agent?: string;
  created: string;
  updated: string;
}

export interface ActivityInput {
  name: string;
  player?: string;
  duration: number;
  success: boolean;
  error?: string;
  arguments?: any;
  user_agent?: string;
}

export interface ActivityListResult {
  items: Activity[];
  page: number;
  perPage: number;
  totalPages: number;
  totalItems: number;
}

export interface ActivitySearchParams {
  page?: number;
  perPage?: number;
  name?: string;
  player?: string;
  success?: boolean;
  sortBy?: string;
}

export function createActivitiesService(pb: PocketBase) {
  return {
    async createActivity(data: ActivityInput): Promise<Activity> {
      const result = await pb.collection("activities").create<Activity>(data);
      return result;
    },

    async searchActivities(params: ActivitySearchParams = {}): Promise<ActivityListResult> {
      const {
        page = 1,
        perPage = 100,
        name,
        player,
        success,
        sortBy = "-created"
      } = params;

      const filters: string[] = [];

      if (name) {
        filters.push(`name ~ "${name}"`);
      }

      if (player) {
        filters.push(`player = "${player}"`);
      }

      if (success !== undefined) {
        filters.push(`success = ${success}`);
      }

      const filterString = filters.length > 0 ? filters.join(" && ") : "";

      const result = await pb.collection("activities").getList<Activity>(page, perPage, {
        filter: filterString,
        sort: sortBy,
        expand: "player",
      });

      return {
        items: result.items,
        page: result.page,
        perPage: result.perPage,
        totalPages: result.totalPages,
        totalItems: result.totalItems,
      };
    },

    async getRecentActivities(limit: number = 100): Promise<Activity[]> {
      const result = await pb.collection("activities").getList<Activity>(1, limit, {
        sort: "-created",
      });
      return result.items;
    },

    async getActivitiesByUser(userId: string, limit: number = 50): Promise<Activity[]> {
      const result = await pb.collection("activities").getList<Activity>(1, limit, {
        filter: `player = "${userId}"`,
        sort: "-created",
      });
      return result.items;
    },

    async getActivitiesByFunction(functionName: string, limit: number = 50): Promise<Activity[]> {
      const result = await pb.collection("activities").getList<Activity>(1, limit, {
        filter: `name = "${functionName}"`,
        sort: "-created",
      });
      return result.items;
    },
  };
}