import type { ProductDetail, ProductListItem, ProductLookup, ProductMedia } from "../@types/products.js";

type ProductRow = {
  product: {
    id: number;
    sku: string;
    name: string;
    slug: string;
    description: string | null;
    basePrice: number;
    discountPercent: number;
    salePrice: number;
    stockQuantity: number;
    status: ProductListItem["status"];
    isFeatured: boolean;
    averageRating: string;
    ratingCount: number;
    createdAt: Date;
    updatedAt: Date;
  };
  brand: ProductLookup | null;
  productType: ProductLookup | null;
  collection: ProductLookup | null;
  frameShape: ProductLookup | null;
  frameColor: (ProductLookup & { hexCode: string | null }) | null;
  ageGroup: ProductLookup | null;
  size: ProductLookup | null;
  primaryMedia: ProductMedia | null;
  media: ProductMedia[];
};

export const toProductListItem = (row: ProductRow): ProductListItem => ({
  ...row.product,
  brand: row.brand,
  productType: row.productType,
  collection: row.collection,
  frameShape: row.frameShape,
  frameColor: row.frameColor,
  ageGroup: row.ageGroup,
  size: row.size,
  primaryMedia: row.primaryMedia,
  media: row.media,
});

export const toProductDetail = (
  row: ProductRow,
  relations: {
    media: ProductMedia[];
    genders: ProductLookup[];
    faceShapes: ProductLookup[];
    lensFeatures: ProductLookup[];
    occasions: ProductLookup[];
  },
): ProductDetail => ({
  ...toProductListItem(row),
  ...relations,
});

export const slugify = (value: string) => {
  return value
    .toLowerCase()
    .trim()
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-+|-+$/g, "")
    .slice(0, 260);
};

export const calculateSalePrice = (basePrice: number, discountPercent: number) => {
  return Math.max(0, Math.round(basePrice - (basePrice * discountPercent) / 100));
};
