import { createMiddleware } from "@tanstack/react-start";
import { getRequest } from "@tanstack/react-start/server";
import { Logger } from "@/lib/logger";
import type { ActivityInput } from "@/lib/pocketbase/services/activities";

const logger = new Logger("Activities");

const recordActivity = (activity: ActivityInput) => {
  import("@/lib/pocketbase/client")
    .then(async ({ pbAdmin }) => {
      await pbAdmin.authPromise;
      await pbAdmin.createActivity(activity);
    })
    .catch((activityError) => {
      logger.error("Failed to record activity", activityError);
    });
};

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 userAgent = request.headers.get('user-agent') || undefined;

  const startTime = Date.now();

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

    recordActivity({
      name: serverFnName,
      player: userId !== 'unknown' ? userId : undefined,
      duration,
      success: true,
      arguments: data,
      user_agent: userAgent,
    });

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

    recordActivity({
      name: serverFnName,
      player: userId !== 'unknown' ? userId : undefined,
      duration,
      success: false,
      error: errorMessage,
      arguments: data,
      user_agent: userAgent,
    });

    throw error;
  }
});
