export interface ImageChanges {
  order: (number | string)[];
  hidden: number[];
  deleted: number[];
  added: Record<string, string>; // e.g. { "new-0": "https://..." }
}

export interface SubmitProductEditArgs {
  pid: number;
  changes: Record<string, unknown>;
  environment: "dev" | "prod";
  imageChanges?: ImageChanges;
}

export interface SubmitProductEditResponse {
  success: boolean;
  message?: string;
  data?: unknown;
  error?: unknown;
}

const DEV_ENDPOINT = "/apiv2-test/product/edit";
const PROD_ENDPOINT = "/apiv2/product/edit";

const isHtmlResponse = (payload: string) => {
  const trimmed = payload.trim();
  return trimmed.startsWith("<!DOCTYPE html") || trimmed.startsWith("<html");
};

export async function submitProductEdit({
  pid,
  changes,
  environment,
  imageChanges,
}: SubmitProductEditArgs): Promise<SubmitProductEditResponse> {
  const targetUrl = environment === "dev" ? DEV_ENDPOINT : PROD_ENDPOINT;

  const product: Record<string, unknown> = { pid, ...changes };
  if (imageChanges) {
    product.image_changes = imageChanges;
  }
  const payload = new URLSearchParams();
  payload.append("products", JSON.stringify([product]));

  const fetchOptions: RequestInit = {
    method: "POST",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded; charset=utf-8",
    },
    body: payload,
  };

  if (environment === "dev") {
    const authToken = import.meta.env.VITE_APIV2_AUTH_TOKEN;
    if (authToken) {
      payload.append("auth", authToken);
      fetchOptions.body = payload;
    }
  } else {
    fetchOptions.credentials = "include";
  }

  let response: Response;
  try {
    response = await fetch(targetUrl, fetchOptions);
  } catch (networkError) {
    throw new Error(
      networkError instanceof Error ? networkError.message : "Network request failed"
    );
  }

  const rawBody = await response.text();

  if (isHtmlResponse(rawBody)) {
    throw new Error(
      "Backend authentication required. Please ensure you are logged into the backend system."
    );
  }

  let parsed: unknown;
  try {
    parsed = JSON.parse(rawBody);
  } catch {
    throw new Error(`Unexpected response from backend (${response.status}).`);
  }

  if (!parsed || typeof parsed !== "object") {
    throw new Error("Empty response from backend");
  }

  const parsedResponse = parsed as Record<string, unknown>;
  return {
    success: Boolean(parsedResponse.success),
    message: typeof parsedResponse.message === "string" ? parsedResponse.message : undefined,
    data: parsedResponse.data,
    error: parsedResponse.error ?? parsedResponse.errors ?? parsedResponse.error_msg,
  };
}
