<?php

namespace App\Models\Ecommerce\Product\Order;

use App\Models\Ecommerce\Channel\Channel;
use App\Models\Ecommerce\Product\Product\Product;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class OrderItem extends Model
{
    use HasFactory;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<string>
     */
    protected $fillable = [
        'product_name',
        'product_id',
        'order_id',
        'channel_id',
        'quantity',
        'unit_price_amount',
        'unit_cost_amount',
    ];

    /**
     * Related order (parent)
     */
    public function order(): BelongsTo
    {
        return $this->belongsTo(Order::class, 'order_id');
    }

    /**
     * Related product
     */
    public function product(): BelongsTo
    {
        return $this->belongsTo(Product::class, 'product_id', 'id');
    }

    /**
     * Related Channel
     */
    public function channel(): BelongsTo
    {
        return $this->belongsTo(Channel::class, 'channel_id', 'id');
    }

    /**
     * Total price
     */
    public function total(): Attribute
    {
        return Attribute::make(
            get: fn () => (float) $this->unit_price_amount * (int) $this->quantity
        );
    }
}
