import { api } from "./client";
import type { ApiResponse } from "./types";
import type { WorkingHours } from "./public-discover";

export type CafeProfileEdit = {
  description: string | null;
  galleryUrls: string[];
  instagramHandle: string | null;
  websiteUrl: string | null;
  workingHours: WorkingHours | null;
};

export type UpdateCafeProfilePayload = {
  description?: string | null;
  instagramHandle?: string | null;
  websiteUrl?: string | null;
  workingHours?: WorkingHours | null;
};

async function unwrap<T>(promise: Promise<{ data: ApiResponse<T> }>): Promise<T> {
  const { data } = await promise;
  if (!data.success || data.data === undefined)
    throw new Error(data.error?.message ?? "Request failed");
  return data.data;
}

export async function fetchCafePublicProfile(cafeId: string): Promise<CafeProfileEdit> {
  return unwrap(api.get<ApiResponse<CafeProfileEdit>>(`/api/cafes/${cafeId}/public-profile`));
}

export async function updateCafePublicProfile(
  cafeId: string,
  payload: UpdateCafeProfilePayload
): Promise<CafeProfileEdit> {
  return unwrap(api.put<ApiResponse<CafeProfileEdit>>(`/api/cafes/${cafeId}/public-profile`, payload));
}

export async function uploadGalleryPhoto(cafeId: string, file: File): Promise<string[]> {
  const form = new FormData();
  form.append("photo", file);
  const { data } = await api.post<ApiResponse<{ galleryUrls: string[] }>>(
    `/api/cafes/${cafeId}/public-profile/gallery`,
    form,
    { headers: { "Content-Type": "multipart/form-data" } }
  );
  if (!data.success || !data.data) throw new Error(data.error?.message ?? "Upload failed");
  return data.data.galleryUrls;
}

export async function removeGalleryPhoto(cafeId: string, url: string): Promise<string[]> {
  const { data } = await api.delete<ApiResponse<{ galleryUrls: string[] }>>(
    `/api/cafes/${cafeId}/public-profile/gallery`,
    { params: { url } }
  );
  if (!data.success || !data.data) throw new Error(data.error?.message ?? "Remove failed");
  return data.data.galleryUrls;
}
