import { cleanupAnonymousUsers } from '~/server/tasks/cleanup';

/**
 * API endpoint to trigger the cleanup of old anonymous users.
 * This endpoint is protected by a secret key passed in the 'x-cleanup-secret' header.
 */
export default defineEventHandler(async (event) => {
  // Read the secret from the request header.
  const secret = getRequestHeader(event, 'x-cleanup-secret');

  // Ensure the secret is present and matches the one in environment variables.
  if (!process.env.CLEANUP_SECRET || secret !== process.env.CLEANUP_SECRET) {
    throw createError({ 
      statusCode: 401, 
      statusMessage: 'Unauthorized. Invalid or missing cleanup secret.' 
    });
  }

  console.log('[API] Cleanup task triggered.');

  try {
    const result = await cleanupAnonymousUsers();
    return { 
      success: true,
      message: `Cleanup successful. Deleted ${result.count} anonymous users.` 
    };
  } catch (error) {
    console.error('[API] Error during cleanup task:', error);
    throw createError({
      statusCode: 500,
      statusMessage: 'Internal Server Error. Failed to execute cleanup task.'
    });
  }
});
