<?php

declare(strict_types=1);

namespace App\Models;

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;

class DberpSupplier extends Model
{
    use GeneratesDberpCode;
    use HasDberpAuditTrail;

    protected $table = 'dberp_suppliers';

    /**
     * @var list<string>
     */
    protected $fillable = [
        'code',
        'name',
        'supplier_category_id',
        'contact_person',
        'mobile',
        'phone',
        'email',
        'address',
        'country_code',
        'region_id',
        'region_name_snapshot',
        'settlement_method',
        'is_enabled',
        'sort_order',
        'remark',
    ];

    protected function casts(): array
    {
        return [
            'supplier_category_id' => 'integer',
            'region_id' => 'integer',
            'is_enabled' => 'boolean',
            'sort_order' => 'integer',
        ];
    }

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

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

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

    public function region(): BelongsTo
    {
        return $this->belongsTo(DberpRegion::class, 'region_id');
    }

    public function supplierCategory(): BelongsTo
    {
        return $this->belongsTo(DberpSupplierCategory::class, 'supplier_category_id');
    }

    public function purchaseOrders(): HasMany
    {
        return $this->hasMany(DberpPurchaseOrder::class, 'supplier_id');
    }

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

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

    public function purchasePriceReferences(): HasMany
    {
        return $this->hasMany(DberpPurchasePriceReferenceSnapshot::class, 'supplier_id');
    }

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

    public function settlementEntries(): HasMany
    {
        return $this->hasMany(DberpSettlementEntry::class, 'counterparty_id')
            ->where('counterparty_type', 'supplier');
    }
}
