<?php

namespace App\DTOs;

use App\Http\Requests\Order\StoreOrderRequest;
use App\Http\Requests\Order\UpdateOrderRequest;
use App\Models\Order;

class OrderDTO extends BaseDTO
{
    public function __construct(
        public readonly ?int $user_id = null,
        public readonly ?string $order_type = null,
        public readonly ?string $order_date = null,
        public readonly ?string $notes = null,
        public readonly ?array $lines = null,
    ) {}

    /**
     * Create DTO from store request.
     */
    public static function fromStoreRequest(StoreOrderRequest $request): self
    {
        $data = $request->validated();
        
        return new self(
            user_id: $data['user_id'] ?? $data['customer_id'],
            order_type: $data['order_type'],
            order_date: $data['order_date'],
            notes: $data['notes'] ?? null,
            lines: $data['lines'],
        );
    }

    /**
     * Create DTO from update request.
     */
    public static function fromUpdateRequest(UpdateOrderRequest $request): self
    {
        $data = $request->validated();
        
        return new self(
            order_date: $data['order_date'] ?? null,
            notes: $data['notes'] ?? null,
            lines: $data['lines'] ?? null,
        );
    }

    /**
     * Create DTO from model.
     */
    public static function fromModel(Order $order): self
    {
        return new self(
            user_id: $order->user_id,
            order_type: $order->order_type,
            order_date: $order->order_date?->format('Y-m-d'),
            notes: $order->notes,
            lines: $order->lines?->toArray(),
        );
    }

    /**
     * Calculate total money amount from lines.
     */
    public function calculateMoneyAmount(): float
    {
        if (!$this->lines) {
            return 0;
        }

        return collect($this->lines)->sum('total_amount') ?? 0;
    }

    /**
     * Check if this is a buy order.
     */
    public function isBuyOrder(): bool
    {
        return $this->order_type === 'BUY';
    }

    /**
     * Check if this is a sell order.
     */
    public function isSellOrder(): bool
    {
        return $this->order_type === 'SELL';
    }
}
