<?php

declare(strict_types=1);

namespace App\Models;

use App\Business\Purchase\Enums\PurchaseOrderStatus;
use App\Business\Settlement\Enums\PayableStatus;
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\Validation\ValidationException;

class DberpPurchaseOrder extends Model
{
    use GeneratesDberpCode;
    use HasDberpAuditTrail;

    protected $table = 'dberp_purchase_orders';

    /**
     * @var list<string>
     */
    protected $fillable = [
        'code',
        'purchase_request_id',
        'purchase_request_code',
        'source_system',
        'external_reference_id',
        'supplier_id',
        'supplier_contact_person_snapshot',
        'supplier_mobile_snapshot',
        'supplier_phone_snapshot',
        'supplier_country_code_snapshot',
        'supplier_region_name_snapshot',
        'supplier_address_snapshot',
        'handler_employee_id',
        'status',
        'business_time',
        'expected_arrival_date',
        'last_arrival_date',
        'total_quantity',
        'total_arrived_quantity',
        'total_rejected_quantity',
        'remaining_arrival_quantity',
        'arrival_progress_status',
        'total_amount',
        'payable_amount',
        'paid_amount',
        'unpaid_amount',
        'payable_status',
        'confirmed_at',
        'closed_at',
        'voided_at',
        'remark',
    ];

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

    protected function casts(): array
    {
        return [
            'purchase_request_id' => 'integer',
            'supplier_id' => 'integer',
            'handler_employee_id' => 'integer',
            'business_time' => 'datetime',
            'expected_arrival_date' => 'date',
            'last_arrival_date' => 'date',
            'total_quantity' => 'decimal:4',
            'total_arrived_quantity' => 'decimal:4',
            'total_rejected_quantity' => 'decimal:4',
            'remaining_arrival_quantity' => 'decimal:4',
            'total_amount' => 'decimal:4',
            'payable_amount' => 'decimal:4',
            'paid_amount' => 'decimal:4',
            'unpaid_amount' => 'decimal:4',
            'confirmed_at' => 'datetime',
            'closed_at' => 'datetime',
            'voided_at' => 'datetime',
        ];
    }

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

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

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

    public function supplier(): BelongsTo
    {
        return $this->belongsTo(DberpSupplier::class, 'supplier_id');
    }

    public function purchaseRequest(): BelongsTo
    {
        return $this->belongsTo(DberpPurchaseRequest::class, 'purchase_request_id');
    }

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

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

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

    public function purchaseExceptions(): HasMany
    {
        return $this->hasMany(DberpPurchaseException::class, 'purchase_order_id');
    }

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

    public function payments(): HasMany
    {
        return $this->hasMany(DberpPaymentOrder::class, 'purchase_order_id');
    }

    public function payableRecord(): HasOne
    {
        return $this->hasOne(DberpPayableRecord::class, 'source_id')->where('source_type', 'purchase_order');
    }

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