import { pbAdmin } from "@/lib/pocketbase/client";
import { createMiddleware } from "@tanstack/react-start";
import { getRequest } from "@tanstack/react-start/server";

export const serverFnLoggingMiddleware = createMiddleware({
  type: "function",
}).server(async ({ next, data, context }) => {
  const request = getRequest();

  const url = new URL(request.url);
  const pathParts = url.pathname.split('/').filter(Boolean);
  const serverFnName = pathParts[pathParts.length - 1] || 'unknown';
  const userId = (context as any)?.metadata?.player_id || 'unknown';

  const startTime = Date.now();

  try {
    const result = await next();
    const duration = Date.now() - startTime;


    try {
      await pbAdmin.authPromise;
      await pbAdmin.createActivity({
        name: serverFnName,
        player: userId !== 'unknown' ? userId : undefined,
        duration,
        success: true,
        arguments: data,
        user_agent: request.headers.get('user-agent') || undefined,
      });
    } catch (activityError) {
    }

    return result;
  } catch (error) {
    const duration = Date.now() - startTime;
    const errorMessage = error instanceof Error ? error.message : String(error);

    try {
      await pbAdmin.authPromise;
      await pbAdmin.createActivity({
        name: serverFnName,
        player: userId !== 'unknown' ? userId : undefined,
        duration,
        success: false,
        error: errorMessage,
        arguments: data,
        user_agent: request.headers.get('user-agent') || undefined,
      });
    } catch (activityError) {
    }

    throw error;
  }
});