/**
 * Result type for server actions that can return errors gracefully
 */
export interface ServerActionResult<T> {
  success: boolean;
  data?: T;
  error?: string;
  status?: number;
}

/**
 * Handle server-side API errors and return graceful error results
 * For critical errors (401, 500), throws an exception
 * For business validation errors (400, 409), returns error result
 */
export async function handleServerApiError(error: any): Promise<never> {
  const statusCode = error?.response?.data?.statusCode || error?.response?.status;
  const message = error?.response?.data?.message || error?.message;

  // Handle 401 Unauthorized - token expired or invalid
  if (statusCode === 401) {
    const authError = new Error("UNAUTHORIZED: Token expired or invalid");
    (authError as any).status = 401;
    throw authError;
  }

  // Handle 403 Forbidden - insufficient permissions
  if (statusCode === 403) {
    const forbiddenError = new Error("FORBIDDEN: Insufficient permissions");
    (forbiddenError as any).status = 403;
    throw forbiddenError;
  }

  // Handle 500 Server errors
  if (statusCode >= 500) {
    throw new Error("Internal server error. Please try again later.");
  }

  // For all other errors (400, 409, etc.), throw with user-friendly message
  // These will be caught by client components and shown in toast
  throw new Error(message || "Something went wrong");
}