<?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;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\Relations\MorphMany;

class DberpCustomer extends Model
{
    use GeneratesDberpCode;
    use HasDberpAuditTrail;

    protected $table = 'dberp_customers';

    /**
     * @var list<string>
     */
    protected $fillable = [
        'code',
        'name',
        'customer_category_id',
        'contact_person',
        'mobile',
        'phone',
        'email',
        'address',
        'country_code',
        'region_id',
        'region_name_snapshot',
        'settlement_method',
        'price_level_code',
        'default_payment_term_days',
        'credit_limit_amount',
        'credit_control_note',
        'salesperson_employee_id',
        'source_platform',
        'external_member_id',
        'integration_sync_status',
        'last_integration_synced_at',
        'is_enabled',
        'sort_order',
        'remark',
    ];

    protected function casts(): array
    {
        return [
            'customer_category_id' => 'integer',
            'region_id' => 'integer',
            'salesperson_employee_id' => 'integer',
            'default_payment_term_days' => 'integer',
            'credit_limit_amount' => 'decimal:4',
            'is_enabled' => 'boolean',
            'sort_order' => 'integer',
            'last_integration_synced_at' => 'datetime',
        ];
    }

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

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

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

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

    /**
     * 同一职员可能对应多条业务员历史行：取 id 最大的一条，供列表展示「业务员主档」展示名。
     */
    public function latestSalespersonProfile(): HasOne
    {
        return $this->hasOne(DberpSalesperson::class, 'employee_id', 'salesperson_employee_id')
            ->latestOfMany();
    }

    public function customerCategory(): BelongsTo
    {
        return $this->belongsTo(DberpCustomerCategory::class, 'customer_category_id');
    }

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

    public function salesOrders(): HasMany
    {
        return $this->hasMany(DberpSalesOrder::class, 'customer_id');
    }

    public function salesQuotes(): HasMany
    {
        return $this->hasMany(DberpSalesQuote::class, 'customer_id');
    }

    public function customerPriceRules(): HasMany
    {
        return $this->hasMany(DberpCustomerPriceRule::class, 'customer_id');
    }

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

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

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