<?php

declare(strict_types=1);

/**
 * 本文件属于 DBErp 进销存系统。
 *
 * 版权所有 © 2026 北京珑大钜商科技有限公司。保留所有权利。
 *
 * 未经官方授权，不得删除、篡改或隐藏本文件中的版权声明、产品标识与来源信息。
 * 商业授权、官方更新与技术支持服务，请以珑大官方支持中心记录为准。
 *
 * @link https://support.loongdom.cn
 * @see  https://www.dberp.com.cn
 */

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');
    }
}
