<?php

declare(strict_types=1);

namespace App\Models;

use App\Business\Sales\Enums\SalesOrderStatus;
use App\Business\Settlement\Enums\ReceivableStatus;
use App\Models\DberpIntegrationMapping;
use App\Models\Concerns\GeneratesDberpCode;
use App\Models\Concerns\HasDberpAuditTrail;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Validation\ValidationException;

class DberpSalesOrder extends Model
{
    use GeneratesDberpCode;
    use HasDberpAuditTrail;

    protected $table = 'dberp_sales_orders';

    /**
     * @var list<string>
     */
    protected $fillable = [
        'code',
        'customer_id',
        'customer_contact_person_snapshot',
        'customer_mobile_snapshot',
        'customer_phone_snapshot',
        'customer_country_code_snapshot',
        'customer_region_name_snapshot',
        'customer_address_snapshot',
        'quote_id',
        'quote_code',
        'handler_employee_id',
        'source_type',
        'source_platform',
        'external_order_id',
        'external_order_no',
        'status',
        'business_time',
        'discount_rate',
        'total_quantity',
        'total_amount',
        'discount_amount',
        'final_amount',
        'receivable_amount',
        'received_amount',
        'unreceived_amount',
        'receivable_status',
        'price_source_type',
        'price_rule_id',
        'payment_term_days',
        'due_date',
        'credit_check_result',
        'credit_override_reason',
        'credit_checked_at',
        'confirmed_at',
        'closed_at',
        'voided_at',
        'imported_at',
        'last_sync_attempt_at',
        'remark',
    ];

    protected static function booted(): void
    {
        static::deleting(function (self $order): void {
            if ($order->status !== SalesOrderStatus::Draft->value) {
                throw ValidationException::withMessages([
                    'status' => __('dberp.errors.sales_delete_only_draft'),
                ]);
            }
        });
    }

    protected function casts(): array
    {
        return [
            'customer_id' => 'integer',
            'quote_id' => 'integer',
            'handler_employee_id' => 'integer',
            'business_time' => 'datetime',
            'discount_rate' => 'decimal:4',
            'total_quantity' => 'decimal:4',
            'total_amount' => 'decimal:4',
            'discount_amount' => 'decimal:4',
            'final_amount' => 'decimal:4',
            'receivable_amount' => 'decimal:4',
            'received_amount' => 'decimal:4',
            'unreceived_amount' => 'decimal:4',
            'price_rule_id' => 'integer',
            'payment_term_days' => 'integer',
            'due_date' => 'date',
            'credit_checked_at' => 'datetime',
            'confirmed_at' => 'datetime',
            'closed_at' => 'datetime',
            'voided_at' => 'datetime',
            'imported_at' => 'datetime',
            'last_sync_attempt_at' => 'datetime',
        ];
    }

    public function getDberpNumberScope(): string
    {
        return 'sales_order';
    }

    public function getDberpAuditActionPrefix(): string
    {
        return 'dberp.sales_order';
    }

    /**
     * @return list<string>
     */
    public function getDberpAuditFields(): array
    {
        return $this->getFillable();
    }

    public function customer(): BelongsTo
    {
        return $this->belongsTo(DberpCustomer::class, 'customer_id');
    }

    public function quote(): BelongsTo
    {
        return $this->belongsTo(DberpSalesQuote::class, 'quote_id');
    }

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

    public function handlerEmployee(): BelongsTo
    {
        return $this->belongsTo(DberpEmployee::class, 'handler_employee_id');
    }

    public function items(): HasMany
    {
        return $this->hasMany(DberpSalesOrderItem::class, 'order_id');
    }

    public function outbounds(): HasMany
    {
        return $this->hasMany(DberpSalesOutboundOrder::class, 'sales_order_id');
    }

    public function returns(): HasMany
    {
        return $this->hasMany(DberpSalesReturnOrder::class, 'sales_order_id');
    }

    public function receipts(): HasMany
    {
        return $this->hasMany(DberpReceiptOrder::class, 'sales_order_id');
    }

    public function receivableRecord(): HasOne
    {
        return $this->hasOne(DberpReceivableRecord::class, 'source_id')->where('source_type', 'sales_order');
    }

    public function integrationMappings(): MorphMany
    {
        return $this->morphMany(DberpIntegrationMapping::class, 'localModel', 'local_model_type', 'local_model_id');
    }

    public function isSettlementBlockedByClosedPolicy(): bool
    {
        return $this->status === SalesOrderStatus::Closed->value;
    }
}