import { Injectable, PipeTransform } from "@nestjs/common";

@Injectable()
export class ParseFormDataJsonPipe implements PipeTransform {
  transform(value: Record<string, unknown>) {
    console.log(value , "value")
    if (!value || typeof value !== "object") {
      return value;
    }

    for (const [key, rawValue] of Object.entries(value)) {
      if (typeof rawValue !== "string") {
        continue;
      }

      const trimmed = rawValue.trim();
      const looksLikeJsonObject = trimmed.startsWith("{") && trimmed.endsWith("}");
      const looksLikeJsonArray = trimmed.startsWith("[") && trimmed.endsWith("]");

      if (!looksLikeJsonObject && !looksLikeJsonArray) {
        continue;
      }

      try {
        (value as Record<string, unknown>)[key] = JSON.parse(trimmed);
      } catch {

        console.log("parsing fails")
        // Keep the original value if parsing fails.
      }
    }
console.log(value , "parsed value");
    return value;
  }
}
