<?php

namespace App\Models\Sales;

use App\Models\Catalog\Product;
use App\Models\Concerns\BelongsToTenant;
use App\Models\Inventory\StockBatch;
use App\Models\Lookups\UnitOfMeasure;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

/**
 * One line on a sales order.
 *
 * Two shapes share this table. A catalog line points at a `product_id` and is
 * priced from the catalog. A custom line (`is_custom`) has no product at all —
 * it is described in words by the customer, made to order, and never touches
 * stock; its price is whatever was quoted. The Custom Orders listing is
 * literally this table filtered to `is_custom`.
 */
class SalesOrderItem extends Model
{
    use BelongsToTenant;

    protected $fillable = [
        'sales_order_id', 'product_id', 'unit_id', 'stock_batch_id', 'is_custom',
        'product_name', 'product_sku', 'custom_description', 'custom_specification',
        'quantity', 'unit_price', 'vat_rate', 'vat_amount', 'gross_total',
        'discount_type', 'discount_value', 'discount_amount', 'line_total',
    ];

    protected function casts(): array
    {
        return [
            'is_custom' => 'boolean',
            'quantity' => 'decimal:4',
            'unit_price' => 'decimal:2',
            'vat_rate' => 'decimal:2',
            'vat_amount' => 'decimal:2',
            'gross_total' => 'decimal:2',
            'discount_value' => 'decimal:2',
            'discount_amount' => 'decimal:2',
            'line_total' => 'decimal:2',
        ];
    }

    public function salesOrder(): BelongsTo
    {
        return $this->belongsTo(SalesOrder::class);
    }

    public function product(): BelongsTo
    {
        return $this->belongsTo(Product::class);
    }

    public function unit(): BelongsTo
    {
        return $this->belongsTo(UnitOfMeasure::class, 'unit_id');
    }

    public function stockBatch(): BelongsTo
    {
        return $this->belongsTo(StockBatch::class, 'stock_batch_id');
    }

    /**
     * @param  Builder<SalesOrderItem>  $query
     * @return Builder<SalesOrderItem>
     */
    public function scopeCustom(Builder $query): Builder
    {
        return $query->where('is_custom', true);
    }
}
