import { apiDelete, apiGet, apiPut } from "@/lib/api/client";
import type { MenuItem } from "@/lib/api/types";

export interface BranchMenuItem extends MenuItem {
  masterPrice: number;
  effectivePrice: number;
  isOverridden: boolean;
  hasPriceOverride: boolean;
}

export function branchMenuItemToMenuItem(row: BranchMenuItem): MenuItem {
  return {
    id: row.id,
    categoryId: row.categoryId,
    name: row.name,
    nameAr: row.nameAr,
    nameEn: row.nameEn,
    description: row.description,
    price: row.effectivePrice,
    imageUrl: row.imageUrl,
    videoUrl: row.videoUrl,
    isAvailable: row.isAvailable,
  };
}

export async function getBranchMenu(
  cafeId: string,
  branchId: string,
  options?: { includeUnavailable?: boolean }
): Promise<BranchMenuItem[]> {
  const qs = options?.includeUnavailable ? "?includeUnavailable=true" : "";
  return apiGet<BranchMenuItem[]>(
    `/api/cafes/${cafeId}/branches/${branchId}/menu${qs}`
  );
}

export async function upsertBranchMenuOverride(
  cafeId: string,
  branchId: string,
  menuItemId: string,
  body: { isAvailable: boolean; priceOverride: number | null }
): Promise<void> {
  await apiPut(
    `/api/cafes/${cafeId}/branches/${branchId}/menu/${menuItemId}/override`,
    body
  );
}

export async function deleteBranchMenuOverride(
  cafeId: string,
  branchId: string,
  menuItemId: string
): Promise<void> {
  await apiDelete(
    `/api/cafes/${cafeId}/branches/${branchId}/menu/${menuItemId}/override`
  );
}
