<?php

namespace App\DTOs;

class OrderLineDTO extends BaseDTO
{
    public function __construct(
        public readonly string $metal_type,
        public readonly float $purity,
        public readonly float $grams,
        public readonly ?float $unit_price = null,
        public readonly ?float $total_amount = null,
        public readonly ?string $notes = null,
    ) {}

    /**
     * Create DTO from array.
     */
    public static function fromArray(array $data): static
    {
        return new static(
            metal_type: $data['metal_type'],
            purity: $data['purity'],
            grams: $data['grams'],
            unit_price: $data['unit_price'] ?? null,
            total_amount: $data['total_amount'] ?? null,
            notes: $data['notes'] ?? null,
        );
    }

    /**
     * Create collection of DTOs from array.
     */
    public static function collectionFromArray(array $lines): array
    {
        return array_map(fn($line) => self::fromArray($line), $lines);
    }

    /**
     * Calculate total amount if not set.
     */
    public function calculateTotalAmount(): ?float
    {
        if ($this->total_amount !== null) {
            return $this->total_amount;
        }

        if ($this->unit_price !== null) {
            return $this->grams * $this->unit_price;
        }

        return null;
    }
}
