<?php

declare(strict_types=1);

namespace App\Models;

use App\Business\Product\DberpDocumentLineUnitService;
use App\Business\Product\ProductBusinessSnapshot;
use App\Models\Concerns\HasDberpDocumentLineUnitRelations;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class DberpSalesOrderItem extends Model
{
    use HasDberpDocumentLineUnitRelations;

    protected $table = 'dberp_sales_order_items';

    /**
     * @var list<string>
     */
    protected $fillable = [
        'order_id',
        'product_id',
        'product_sku_id',
        'product_code',
        'product_name',
        'sku_code',
        'spec_text',
        'unit_id',
        'unit_name',
        'quantity',
        'unit_price',
        'line_amount',
        'discount_amount',
        'final_amount',
        'shipped_quantity',
        'returned_quantity',
        'base_quantity',
        'base_shipped_quantity',
        'source_quote_item_id',
        'price_source_type',
        'price_source_label',
        'price_rule_id',
        'matched_unit_price',
        'reference_unit_price',
        'recent_transaction_unit_price',
        'recent_transaction_date',
        'external_line_id',
        'external_product_id',
        'external_sku',
        'base_unit_id',
        'auxiliary_unit_id',
        'is_auxiliary_unit',
        'auxiliary_unit_quantity',
        'base_unit_quantity',
        'sort_order',
        'remark',
    ];

    protected static function booted(): void
    {
        static::saving(function (self $item): void {
            if ($item->product_sku_id !== null) {
                $sku = DberpProductSku::query()->with(['product.unit'])->find($item->product_sku_id);
                if ($sku instanceof DberpProductSku) {
                    $snap = ProductBusinessSnapshot::identityFromSku($sku);
                    $item->forceFill([
                        'product_id' => $snap['product_id'],
                        'product_code' => $snap['product_code'],
                        'product_name' => $snap['product_name'],
                        'sku_code' => $snap['sku_code'],
                        'spec_text' => $snap['spec_text'],
                    ]);
                }
            }

            DberpDocumentLineUnitService::applySnapshotsToLine($item);

            $quantity = (float) ($item->quantity ?? 0);
            $unitPrice = (float) ($item->unit_price ?? 0);
            $discountAmount = (float) ($item->discount_amount ?? 0);
            $lineAmount = $quantity * $unitPrice;

            $item->setAttribute('line_amount', number_format($lineAmount, 4, '.', ''));
            $item->setAttribute('final_amount', number_format($lineAmount - $discountAmount, 4, '.', ''));
        });

        static::saved(function (self $item): void {
            $item->order?->forceFill([
                'total_quantity' => (string) $item->order->items()->sum('quantity'),
                'total_amount' => (string) $item->order->items()->sum('line_amount'),
                'discount_amount' => (string) $item->order->items()->sum('discount_amount'),
                'final_amount' => (string) $item->order->items()->sum('final_amount'),
            ])->save();
        });

        static::deleted(function (self $item): void {
            $item->order?->forceFill([
                'total_quantity' => (string) $item->order->items()->sum('quantity'),
                'total_amount' => (string) $item->order->items()->sum('line_amount'),
                'discount_amount' => (string) $item->order->items()->sum('discount_amount'),
                'final_amount' => (string) $item->order->items()->sum('final_amount'),
            ])->save();
        });
    }

    protected function casts(): array
    {
        return [
            'order_id' => 'integer',
            'product_id' => 'integer',
            'product_sku_id' => 'integer',
            'unit_id' => 'integer',
            'base_unit_id' => 'integer',
            'auxiliary_unit_id' => 'integer',
            'is_auxiliary_unit' => 'boolean',
            'auxiliary_unit_quantity' => 'decimal:6',
            'base_unit_quantity' => 'decimal:6',
            'quantity' => 'decimal:4',
            'unit_price' => 'decimal:4',
            'line_amount' => 'decimal:4',
            'discount_amount' => 'decimal:4',
            'final_amount' => 'decimal:4',
            'shipped_quantity' => 'decimal:4',
            'returned_quantity' => 'decimal:4',
            'base_quantity' => 'decimal:4',
            'base_shipped_quantity' => 'decimal:4',
            'source_quote_item_id' => 'integer',
            'price_rule_id' => 'integer',
            'matched_unit_price' => 'decimal:4',
            'reference_unit_price' => 'decimal:4',
            'recent_transaction_unit_price' => 'decimal:4',
            'recent_transaction_date' => 'date',
            'sort_order' => 'integer',
        ];
    }

    public function order(): BelongsTo
    {
        return $this->belongsTo(DberpSalesOrder::class, 'order_id');
    }

    public function product(): BelongsTo
    {
        return $this->belongsTo(DberpProduct::class, 'product_id');
    }

    public function productSku(): BelongsTo
    {
        return $this->belongsTo(DberpProductSku::class, 'product_sku_id');
    }

    public function sourceQuoteItem(): BelongsTo
    {
        return $this->belongsTo(DberpSalesQuoteItem::class, 'source_quote_item_id');
    }

    public function priceRule(): BelongsTo
    {
        return $this->belongsTo(DberpCustomerPriceRule::class, 'price_rule_id');
    }
}
