<?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 DberpReceivableRecord extends Model
{
    use GeneratesDberpCode;
    use HasDberpAuditTrail;

    protected $table = 'dberp_receivable_records';

    /**
     * @var list<string>
     */
    protected $fillable = [
        'code',
        'customer_id',
        'source_type',
        'source_id',
        'source_document_no',
        'source_document_status',
        'business_date',
        'due_date',
        'handler_employee_id',
        'source_system',
        'external_document_no',
        'external_reference_id',
        'original_amount',
        'adjusted_amount',
        'written_off_amount',
        'remaining_amount',
        'record_status',
        'formed_at',
        'last_write_off_at',
        'closed_at',
        'voided_at',
        'remark',
    ];

    protected function casts(): array
    {
        return [
            'customer_id' => 'integer',
            'source_id' => 'integer',
            'handler_employee_id' => 'integer',
            'business_date' => 'datetime',
            'due_date' => 'date',
            'original_amount' => 'decimal:4',
            'adjusted_amount' => 'decimal:4',
            'written_off_amount' => 'decimal:4',
            'remaining_amount' => 'decimal:4',
            'formed_at' => 'datetime',
            'last_write_off_at' => 'datetime',
            'closed_at' => 'datetime',
            'voided_at' => 'datetime',
        ];
    }

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

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

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

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

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

    public function salesOrder(): BelongsTo
    {
        return $this->belongsTo(DberpSalesOrder::class, 'source_id');
    }

    public function writeOffLines(): HasMany
    {
        return $this->hasMany(DberpSettlementWriteOffLine::class, 'receivable_record_id');
    }

    public function adjustments(): HasMany
    {
        return $this->hasMany(DberpSettlementAdjustment::class, 'receivable_record_id');
    }
}