import { Product } from 'src/entities/product.entity';

const productKeys = [
  'ebayListingId', // thêm dòng này
  'id',
  'code',
  'listImage',
  'package_contain',
  'description',
  'shortDescription',
  'title',
  'category',
  'price',
  'conditionEbay',
  'condition',
  'manufactor',
  'location',
  'listingId',
  'name',
  'createdAt',
  'updatedAt',
] as const;

type ProductInput = {
  [K in (typeof productKeys)[number]]?: Product[K] | null;
};

export function mapToProduct(
  raw: Record<string, any>,
): ProductInput & { ebayListingId: string } {
  const mapped: any = {};

  mapped.ebayListingId = raw.ebayListingId; // bắt buộc map khóa chính

  for (const key of productKeys) {
    const value = raw[key];

    if (value !== undefined && value !== null) {
      if (key === 'createdAt' || key === 'updatedAt') {
        mapped[key] = new Date(value);
      } else if (key === 'listImage' || key === 'package_contain') {
        mapped[key] = Array.isArray(value) ? value.map(String) : [];
      } else {
        mapped[key] = value;
      }
    } else {
      mapped[key] =
        key === 'listImage' || key === 'package_contain' ? [] : null;
    }
  }

  return mapped;
}
