import { api } from "@/config";
import { API_CREW, API_GET_PHOTO, API_SEARCH_CREW } from "@/constants";

export async function newCrew(body: Model.NewCrewAPIRequest) {
  return api.post(API_CREW, body);
}

export async function searchCrew(personal_id: string) {
  return api.get<Model.TripCrewPerson>(`${API_SEARCH_CREW}/${personal_id}`);
}

export async function updateCrewInfo(
  personalId: string,
  body: Model.UpdateCrewAPIRequest
) {
  return api.put(`${API_CREW}/${personalId}`, body);
}

export async function queryCrewImage(personal_id: string) {
  return await api.get(`${API_GET_PHOTO}/people/${personal_id}/main`, {
    responseType: "arraybuffer",
  });
}

// Upload ảnh thuyền viên
// Hỗ trợ các định dạng: HEIC, jpg, jpeg, png
export async function uploadCrewImage(personalId: string, imageUri: string) {
  // Lấy tên file và extension từ URI
  const uriParts = imageUri.split("/");
  const fileName = uriParts[uriParts.length - 1];

  // Xác định MIME type dựa trên extension
  const extension = fileName.split(".").pop()?.toLowerCase() || "jpg";
  let mimeType = "image/jpeg";

  switch (extension) {
    case "heic":
      mimeType = "image/heic";
      break;
    case "heif":
      mimeType = "image/heif";
      break;
    case "png":
      mimeType = "image/png";
      break;
    case "gif":
      mimeType = "image/gif";
      break;
    case "webp":
      mimeType = "image/webp";
      break;
    case "jpg":
    case "jpeg":
    default:
      mimeType = "image/jpeg";
      break;
  }

  // Tạo FormData để upload
  const formData = new FormData();
  formData.append("file", {
    uri: imageUri,
    name: fileName,
    type: mimeType,
  } as any);

  // Debug logs
  console.log("📤 Upload params:");
  console.log("  - URI:", imageUri);
  console.log("  - fileName:", fileName);
  console.log("  - mimeType:", mimeType);
  console.log("  - endpoint:", `${API_GET_PHOTO}/people/${personalId}/main`);

  // Phải set Content-Type header cho React Native
  return api.post(`${API_GET_PHOTO}/people/${personalId}/main`, formData, {
    headers: {
      "Content-Type": "multipart/form-data",
    },
  });
}
