export interface BaseResponse<T = unknown> {
  statusCode?: number;
  success: boolean;
  data: T;
  message?: string;
}

export interface Category {
  id: string;
  createdAt: string;
  updatedAt: string;
  deletedAt: string | null;
  parent: string | null;
  title: string;
  isActive: boolean;
  shop: string;
  avatarUrl: string | null;
  order: number | null;
  children: Category[];
}

export type CategoriesResponse = BaseResponse<Category[]>;

export type ProductImage = string | { url: string; alt?: string | null };

/** Category as nested in product list API */
export interface ProductCategory {
  id: string;
  createdAt: string;
  updatedAt: string;
  deletedAt: string | null;
  parent: string | null;
  title: string;
  isActive: boolean;
  shop: string;
  avatarUrl: string | null;
  order: number | null;
}

export interface ProductVariant {
  id: string;
  createdAt: string;
  updatedAt: string;
  deletedAt: string | null;
  product: string;
  value: string;
  price: number;
}

export interface Product {
  id: string;
  createdAt: string;
  updatedAt: string;
  deletedAt: string | null;
  shop: string;
  category: ProductCategory;
  attribute: string | null;
  title: string;
  desc: string;
  order: number | null;
  isActive: boolean;
  images: string[];
  score: number | null;
  discount: number;
  isSpecialOffer: boolean;
  price: number | null;
  variants: ProductVariant[];
  /** Backward compatibility / other APIs */
  name?: string;
  description?: string;
  content?: string[] | string | null;
  image?: string | null;
  inPlaceServe?: boolean;
  pickupServe?: boolean;
  points?: number | null;
  rate?: number | null;
  prepareTime?: number | null;
  isFavorite?: boolean;
}

export type ProductsResponse = BaseResponse<Product[]>;
export type ProductResponse = BaseResponse<Product>;

/** محصول بدون تنوع: attribute خالی → قیمت از اولین واریانت */
export function hasVariants(product: Product): boolean {
  return Boolean(product.attribute?.trim());
}

/** شناسه‌ای که برای سبد/API استفاده می‌شود: همیشه variantId (اگر بدون تنوع، همان واریانت اول) */
export function getPrimaryVariantId(product: Product): string | null {
  const first = product.variants?.[0];
  return first?.id ?? null;
}

/** قیمت مؤثر: بدون تنوع = قیمت واریانت اول، با تنوع = product.price یا اولین واریانت */
export function getProductEffectivePrice(product: Product): number {
  if (product.price != null && product.price > 0) return product.price;
  const first = product.variants?.[0];
  return first?.price ?? 0;
}

export interface NotificationsCountData {
  count: number;
}

export type NotificationsCountResponse = BaseResponse<NotificationsCountData>;
