/**
 * Human-Centered Error & Feedback Translation Engine
 * Converts raw database codes, network failures, and technical errors into actionable user advice.
 */

export interface HumanizedFeedback {
  title: string;
  message: string;
  actionHint?: string;
}

export function translateError(error: unknown, fallbackMessage = "An unexpected error occurred."): HumanizedFeedback {
  if (!error) {
    return {
      title: "Notice",
      message: fallbackMessage,
    };
  }

  const errString = typeof error === "string" ? error : (error as any)?.message || JSON.stringify(error);
  const errCode = (error as any)?.code || "";

  // 1. PostgreSQL & Supabase Database Error Codes
  if (errCode === "23505" || errString.includes("unique constraint") || errString.includes("already exists")) {
    return {
      title: "Duplicate Entry",
      message: "A record with these details already exists in the system.",
      actionHint: "Please check the reference code, title, or email address and try a unique value.",
    };
  }

  if (errCode === "23503" || errString.includes("foreign key")) {
    return {
      title: "Related Record Missing",
      message: "This action depends on a related agency, user, or location that was not found.",
      actionHint: "Please ensure your agency and location selections are valid before saving.",
    };
  }

  if (errCode === "42501" || errString.includes("permission denied") || errString.includes("row-level security")) {
    return {
      title: "Access Restricted",
      message: "You don't have permission to modify or view this specific record.",
      actionHint: "Please sign in with an account that has administrative or owner rights.",
    };
  }

  if (errCode === "PGRST116" || errString.includes("not found")) {
    return {
      title: "Listing Not Found",
      message: "The requested property listing or record could not be located. It may have been archived or removed.",
      actionHint: "Return to the property directory to explore active listings.",
    };
  }

  // 2. Authentication & Session Errors
  if (errString.includes("clerk") || errString.includes("unauthorized") || errString.includes("auth")) {
    return {
      title: "Session Expired",
      message: "Your login session has timed out or could not be verified.",
      actionHint: "Please sign in again to continue managing your properties.",
    };
  }

  // 3. File & Image Upload Errors
  if (errString.includes("file size") || errString.includes("too large")) {
    return {
      title: "Image Size Too Large",
      message: "One or more selected photos exceed the maximum allowed size of 10MB.",
      actionHint: "Please compress your photos or choose standard JPEG/WebP formats.",
    };
  }

  if (errString.includes("unsupported file") || errString.includes("mime")) {
    return {
      title: "Unsupported Image Format",
      message: "The uploaded file format is not supported.",
      actionHint: "Please upload standard JPG, PNG, or WebP photo files.",
    };
  }

  // 4. Network & Payment Errors
  if (errString.includes("fetch failed") || errString.includes("network") || errString.includes("ECONNREFUSED")) {
    return {
      title: "Connection Interrupted",
      message: "We were unable to communicate with our server. Please check your internet connection.",
      actionHint: "Ensure you are online and click Try Again.",
    };
  }

  if (errString.includes("paystack") || errString.includes("payment")) {
    return {
      title: "Payment Processing Notice",
      message: "We encountered a temporary delay with the payment gateway.",
      actionHint: "Your funds are safe. Please check your account history or retry in a few moments.",
    };
  }

  // Fallback for general unhandled errors
  return {
    title: "Action Could Not Complete",
    message: errString.length < 150 ? errString : fallbackMessage,
    actionHint: "Please review your inputs or try again shortly.",
  };
}
