import type { Product as PrismaProduct, DesignProof as PrismaDesignProof } from '@prisma/client';
import type { ProductDTO, ProofDTO } from './types';
import { getEffectivePrice, type ActivePromotion } from './pricing';

export function toProductDTO(p: PrismaProduct, activePromotions: ActivePromotion[] = []): ProductDTO {
  const { onSale, price, originalPrice } = getEffectivePrice(p, activePromotions);
  return {
    id: p.id,
    slug: p.slug,
    name: p.name,
    category: p.category,
    description: p.description,
    basePrice: p.basePrice,
    personalisedPrice: p.personalisedPrice,
    colors: JSON.parse(p.colors),
    colorPhotos: p.colorPhotos ? JSON.parse(p.colorPhotos) : {},
    colorPhotosBack: p.colorPhotosBack ? JSON.parse(p.colorPhotosBack) : {},
    sizes: p.sizes ? JSON.parse(p.sizes) : [],
    mockup: p.mockup,
    printArea: JSON.parse(p.printArea),
    printAreaBack: p.printAreaBack ? JSON.parse(p.printAreaBack) : null,
    printAreaWidthMm: p.printAreaWidthMm,
    printAreaHeightMm: p.printAreaHeightMm,
    referenceWidthCm: p.referenceWidthCm,
    referenceHeightCm: p.referenceHeightCm,
    imageUrl: p.imageUrl,
    imageUrlBack: p.imageUrlBack,
    photoRecolorable: p.photoRecolorable,
    showOnPersonalised: p.showOnPersonalised,
    showOnProducts: p.showOnProducts,
    createdAt: p.createdAt.toISOString(),
    onSale,
    effectivePrice: price,
    originalPrice,
  };
}

export function toProofDTO(p: PrismaDesignProof & { product: PrismaProduct }): ProofDTO {
  return {
    id: p.id,
    productId: p.productId,
    productName: p.product.name,
    productSlug: p.product.slug,
    customerName: p.customerName,
    customerEmail: p.customerEmail,
    color: p.color,
    quantity: p.quantity,
    unitPrice: p.unitPrice,
    imageDataUrl: p.imageDataUrl,
    note: p.note,
    status: p.status as ProofDTO['status'],
    createdAt: p.createdAt.toISOString(),
  };
}
