import {
  RecordOfficerOutgoingRecordsListResponse,
  RecordOfficerRecordsListResponse,
} from "@/record-management/dto/recordOfficer/recordOfficerRecordDto";
import recordAxiosInstance from "@/shared/services/recordAxiosInstance";
import Cookies from "js-cookie";
import { withHeaders } from "./withHeaders";

export interface OutgoingRecordQueryParams {
  orderBy?: string;
  take?: number;
  skip?: number;
  order?: string;
  referenceNumber?: string;
  subject?: string;
  receiverPosition?: string;
  receiverEmployee?: string;
  sendingPosition?: string;
  fromDispatchedDate?: string;
  toDispatchedDate?: string;
  from?: string;
  to?: string;
  status?: string;
  recordBoxStatus?: string;
  isUrgent?: boolean;
  isRO?: boolean;
  nonSmartOfficeRecordStatus?: string;
  recordTypeKey?: string;
}

export const dispatchedRecords = async (
  params?: OutgoingRecordQueryParams,
): Promise<RecordOfficerOutgoingRecordsListResponse> => {
  try {
    const response = await recordAxiosInstance.get(
      `/outgoing-instances/dispatched`,
      {
        params,
        headers: withHeaders(),
      },
    );

    return response.data;
  } catch (error) {
    throw new Error("Failed to fetch dispatched records");
  }
};

export const toBeDispatchedRecords = async (
  params?: OutgoingRecordQueryParams,
): // params?: OutgoingRecordQueryParams
Promise<any> => {
  try {
    const response = await recordAxiosInstance.get(
      `/outgoing-instances/to-be-dispatched`,
      {
        params,
        headers: withHeaders(),
      },
    );

    return response.data;
  } catch (error) {
    throw new Error("Failed to fetch to-be-dispatched records");
  }
};
export const addReplies = async (body: any): Promise<any> => {
  try {
    const response = await recordAxiosInstance.post("/record-replies", body, {
      headers: withHeaders(),
    });
    return response.data;
  } catch (error) {
    throw new Error("Failed to add replies");
  }
};
export const deleteReplies = async (replyId: string): Promise<any> => {
  try {
    const response = await recordAxiosInstance.delete(
      `/record-replies/${replyId}`,
      {
        headers: withHeaders(),
      },
    );
    return response.data;
  } catch (error) {
    throw new Error("Failed to delete replies");
  }
};
export const editReplies = async (replyId: string, body: any): Promise<any> => {
  try {
    const response = await recordAxiosInstance.put(
      `/record-replies/${replyId}`,
      body,
      {
        headers: withHeaders(),
      },
    );
    return response.data;
  } catch (error) {
    throw new Error("Failed to edit replies");
  }
};
export const dispatchRecord = async (body: any): Promise<any> => {
  try {
    const response = await recordAxiosInstance.patch(
      "outgoing-instances/dispatch",
      body,
      {
        headers: withHeaders(),
        responseType: "blob", // to handle PDF blob if returned
      },
    );

    const contentType = String(response.headers["content-type"] ?? "");
    const contentLength = String(response.headers["content-length"] ?? "");

    if (contentType.includes("application/pdf")) {
      const pdfBlob = new Blob([response.data], { type: "application/pdf" });
      const pdfUrl = window.URL.createObjectURL(pdfBlob);
      window.open(pdfUrl, "_blank");
      return;
    }

    if (contentLength === "0" || response.status === 204) {
      return;
    }

    if (contentType.includes("application/json")) {
      // Manually parse blob as JSON
      const text = await response.data.text();
      return JSON.parse(text);
    }

    return;
  } catch (error: any) {
    console.error("Error dispatching record:", error);
    // ⛔️ don’t wrap → let useErrorHandler handle parsing
    throw new Error("Failed to dispatch record");
  }
};
