part of '../product_dtos.dart';

@freezed
class ProductDto with _$ProductDto {
  const ProductDto._();

  const factory ProductDto({
    @JsonKey(name: 'id') String? id,
    @JsonKey(name: 'organization_id') String? organizationId,
    @JsonKey(name: 'category_id') String? categoryId,
    @JsonKey(name: 'sku') String? sku,
    @JsonKey(name: 'name') String? name,
    @JsonKey(name: 'description') String? description,
    @JsonKey(name: 'price') int? price,
    @JsonKey(name: 'cost') int? cost,
    @JsonKey(name: 'business_type') String? businessType,
    @JsonKey(name: 'image_url') String? imageUrl,
    @JsonKey(name: 'printer_type') String? printerType,
    @JsonKey(name: 'metadata') Map<String, dynamic>? metadata,
    @JsonKey(name: 'is_active') bool? isActive,
    @JsonKey(name: 'created_at') DateTime? createdAt,
    @JsonKey(name: 'updated_at') DateTime? updatedAt,
    @JsonKey(name: 'variants') List<ProductVariantDto>? variants,
  }) = _ProductDto;

  factory ProductDto.fromJson(Map<String, dynamic> json) =>
      _$ProductDtoFromJson(json);

  /// DTO -> Domain (isi default kalau null)
  Product toDomain() => Product(
    id: id ?? '',
    organizationId: organizationId ?? '',
    categoryId: categoryId ?? '',
    sku: sku ?? '',
    name: name ?? '',
    description: description ?? '',
    price: price ?? 0,
    cost: cost ?? 0,
    businessType: businessType ?? '',
    imageUrl: imageUrl ?? '',
    printerType: printerType ?? '',
    metadata: metadata ?? {},
    isActive: isActive ?? false,
    createdAt: createdAt ?? DateTime.now(),
    updatedAt: updatedAt ?? DateTime.now(),
    variants: variants?.map((v) => v.toDomain()).toList() ?? [],
  );

  /// Domain -> DTO
  factory ProductDto.fromDomain(Product product) => ProductDto(
    id: product.id,
    organizationId: product.organizationId,
    categoryId: product.categoryId,
    sku: product.sku,
    name: product.name,
    description: product.description,
    price: product.price,
    cost: product.cost,
    businessType: product.businessType,
    imageUrl: product.imageUrl,
    printerType: product.printerType,
    metadata: product.metadata,
    isActive: product.isActive,
    createdAt: product.createdAt,
    updatedAt: product.updatedAt,
    variants: product.variants
        .map((v) => ProductVariantDto.fromDomain(v))
        .toList(),
  );
}
