import api from "./api";

/* =======================
   TYPES
======================= */

export type ImagingType =
  | "CT"
  | "PET-CT"
  | "MRI"
  | "X-RAY"
  | "ULTRASOUND";

export interface ImagingReport {
  id: number;
  title: string;
  type: ImagingType;
  description?: string;

  url?: string;
  file_url?: string;
  file_name?: string;
  file_size?: number;

  doctorId?: number;
  doctorName?: string;

  patientId?: string;
  patientName?: string;

  createdAt?: string;
  updatedAt?: string;
}

/* =======================
   CREATE
======================= */

export const createImagingReport = async (
  formData: FormData
): Promise<ImagingReport> => {
  const response = await api.post("/imaging", formData);
  return response.data;
};

/* =======================
   FETCH
======================= */

export const getImagingReports = async (
  patientId?: string
): Promise<ImagingReport[]> => {
  const params = patientId ? { patientId } : {};
  const response = await api.get("/imaging", { params });

  let reports: any[] = [];

  if (Array.isArray(response.data)) {
    reports = response.data;
  } else if (Array.isArray(response.data?.data)) {
    reports = response.data.data;
  } else {
    return [];
  }

  return reports.map((report: any) => {
    const url = report.url || report.file_url;

    let doctorName =
      report.doctorName ||
      report.Doctor?.Doctor?.full_name ||
      report.Doctor?.full_name ||
      report.doctor?.full_name ||
      null;

    let patientName = report.patientName;
    if (!patientName && report.Patient) {
      patientName = `${report.Patient.forename || ""} ${
        report.Patient.surname || ""
      }`.trim();
    }

   

    return {
      id: report.id,
      title: report.title,
      type: report.type,
      description: report.description || "",

      url,
      file_url: url,
      file_name:
        report.file_name ||
        report.fileName ||
        (url ? url.split("/").pop() : undefined),
      file_size: report?.filesize,

      doctorId: report.doctorId,
      doctorName,

      patientId: report.patientId,
      patientName,

      createdAt: report.createdAt || report.created_at,
      updatedAt: report.updatedAt || report.updated_at,
    };
  });
};

/* =======================
   UPDATE
======================= */

export const updateImagingReport = async (
  imagingId: number,
  formData: FormData
): Promise<ImagingReport> => {
  const response = await api.put(`/imaging/${imagingId}`, formData);
  return response.data;
};

/* =======================
   DELETE
======================= */

export const deleteImagingReport = async (
  imagingId: number
): Promise<void> => {
  await api.delete(`/imaging/${imagingId}`);
};



export const viewImagingReport = async (
  imagingId: number | string
): Promise<string> => {
  const response = await api.get(`/imaging/${imagingId}/view`);

  const url =
    response.data?.data?.url ||
    response.data?.url;

  if (!url) {
    throw new Error("Failed to open report");
  }

  return url;
};
