/**
 * In-memory store for custom app data from thread conversations.
 *
 * POST: stores customized app data (from AI thread responses)
 * GET:  returns and consumes custom data for a given app ID
 *
 * The /api/mcp-apps route checks this store BEFORE falling back to demo data.
 * This is the bridge between thread conversations and iframe rendering.
 */

// Shared in-memory store — exported so mcp-apps route can access it
// Map<appId, { data: any, timestamp: number }>
const customAppDataStore = new Map<string, { data: unknown; timestamp: number }>();

// Export for direct access from mcp-apps route
export function getCustomAppData(appId: string): unknown | null {
  const entry = customAppDataStore.get(appId);
  if (!entry) return null;

  // Data expires after 5 minutes (safety net)
  if (Date.now() - entry.timestamp > 5 * 60 * 1000) {
    customAppDataStore.delete(appId);
    return null;
  }

  return entry.data;
}

export async function POST(request: Request) {
  try {
    const body = await request.json();
    const { appId, data } = body as { appId: string; data: unknown };

    if (!appId || !data) {
      return Response.json(
        { error: "Missing appId or data" },
        { status: 400 }
      );
    }

    customAppDataStore.set(appId, {
      data,
      timestamp: Date.now(),
    });

    return Response.json({ ok: true });
  } catch {
    return Response.json({ error: "Invalid JSON" }, { status: 400 });
  }
}

export async function GET(request: Request) {
  const url = new URL(request.url);
  const appId = url.searchParams.get("app");

  if (!appId) {
    return Response.json(
      { error: "Missing app parameter" },
      { status: 400 }
    );
  }

  const data = getCustomAppData(appId);

  if (data) {
    // Consume the data (one-time use — next reload gets fresh data or demo)
    // Actually, DON'T consume — keep it so iframe can reload multiple times
    // customAppDataStore.delete(appId);
    return Response.json({ data });
  }

  return Response.json({ data: null });
}

export async function DELETE(request: Request) {
  const url = new URL(request.url);
  const appId = url.searchParams.get("app");

  if (appId) {
    customAppDataStore.delete(appId);
  } else {
    customAppDataStore.clear();
  }

  return Response.json({ ok: true });
}
