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

    protected $table = 'dberp_settlement_statements';

    /**
     * @var list<string>
     */
    protected $fillable = [
        'code',
        'settlement_side',
        'counterparty_type',
        'counterparty_id',
        'counterparty_name',
        'statement_date',
        'period_start_date',
        'period_end_date',
        'opening_balance',
        'period_increase_amount',
        'period_decrease_amount',
        'closing_balance',
        'item_count',
        'statement_status',
        'handler_employee_id',
        'confirmed_at',
        'voided_at',
        'last_exported_at',
        'last_exported_by',
        'source_system',
        'external_document_no',
        'external_reference_id',
        'remark',
    ];

    protected function casts(): array
    {
        return [
            'counterparty_id' => 'integer',
            'statement_date' => 'date',
            'period_start_date' => 'date',
            'period_end_date' => 'date',
            'opening_balance' => 'decimal:4',
            'period_increase_amount' => 'decimal:4',
            'period_decrease_amount' => 'decimal:4',
            'closing_balance' => 'decimal:4',
            'item_count' => 'integer',
            'handler_employee_id' => 'integer',
            'confirmed_at' => 'datetime',
            'voided_at' => 'datetime',
            'last_exported_at' => 'datetime',
            'last_exported_by' => 'integer',
        ];
    }

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

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

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

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

    public function exportedBy(): BelongsTo
    {
        return $this->belongsTo(User::class, 'last_exported_by');
    }

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