import { apiFetch } from '@/utils/api';
export interface ImageChanges {
  order: (number | string)[];
  hidden: number[];
  show: number[];
  delete: number[];
  add: Record<string, string>; // e.g. { "new-0": "https://..." }
}

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

export interface SubmitImageChangesArgs {
  pid: number;
  imageChanges: ImageChanges;
  environment: "dev" | "prod";
}

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,
}: SubmitProductEditArgs): Promise<SubmitProductEditResponse> {
  const targetUrl = environment === "dev" ? DEV_ENDPOINT : PROD_ENDPOINT;

  const product: Record<string, unknown> = { pid, ...changes };
  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 apiFetch(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,
  };
}

export type TaxonomyType = "cats" | "themes" | "colors";

export interface SubmitTaxonomySetArgs {
  pid: number;
  type: TaxonomyType;
  ids: number[];
  environment: "dev" | "prod";
}

export async function submitTaxonomySet({
  pid,
  type,
  ids,
  environment,
}: SubmitTaxonomySetArgs): Promise<SubmitProductEditResponse> {
  const base = environment === "dev" ? "/apiv2-test" : "/apiv2";
  const targetUrl = `${base}/product/${type}/${pid}/set`;

  const fetchOptions: RequestInit = {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(ids),
  };

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

  let response: Response;
  try {
    response = await apiFetch(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,
  };
}

const DEV_IMAGE_ENDPOINT = "/apiv2-test/product/image_changes";
const PROD_IMAGE_ENDPOINT = "/apiv2/product/image_changes";

export async function submitImageChanges({
  pid,
  imageChanges,
  environment,
}: SubmitImageChangesArgs): Promise<SubmitProductEditResponse> {
  const targetUrl = environment === "dev" ? DEV_IMAGE_ENDPOINT : PROD_IMAGE_ENDPOINT;

  const body = { pid, image_changes: imageChanges };

  const fetchOptions: RequestInit = {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(body),
  };

  if (environment === "dev") {
    const authToken = import.meta.env.VITE_APIV2_AUTH_TOKEN;
    if (authToken) {
      (body as Record<string, unknown>).auth = authToken;
      fetchOptions.body = JSON.stringify(body);
    }
  } else {
    fetchOptions.credentials = "include";
  }

  let response: Response;
  try {
    response = await apiFetch(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,
  };
}
