<?php

namespace App\Models\PensionCase;

use Database\Factories\PensionCase\PensionCaseInterimFactory;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class PensionCaseInterim extends Model {
    use HasFactory;

    // Append-only - only created_at, no updated_at
    public $timestamps = false;

    protected static function newFactory(): PensionCaseInterimFactory {
        return PensionCaseInterimFactory::new();
    }

    protected $table = 'pension_case_interims';

    protected $fillable = [
        'pension_case_id',
        'interim_number',
        'interim_date',
        'interim_amount',
        'interim_capped_amount',
        'net_to_client',
        'vat_amount',
        'cpf_fee_gross',
        'cpf_fee_gross_capped',
        'cpf_fee_net',
        'cpf_fee_net_capped',
    ];

    protected $casts = [
        'interim_date' => 'date',
        'interim_amount' => 'decimal:2',
        'interim_capped_amount' => 'decimal:2',
        'net_to_client' => 'decimal:2',
        'vat_amount' => 'decimal:2',
        'cpf_fee_gross' => 'decimal:2',
        'cpf_fee_gross_capped' => 'decimal:2',
        'cpf_fee_net' => 'decimal:2',
        'cpf_fee_net_capped' => 'decimal:2',
        'created_at' => 'datetime',
    ];

    protected static function booted(): void {
        // Auto-assign interim_number as next sequential number for the case
        static::creating(function (PensionCaseInterim $interim) {
            if (empty($interim->interim_number)) {
                $max = static::where('pension_case_id', $interim->pension_case_id)->max('interim_number');
                $interim->interim_number = ($max ?? 0) + 1;
            }

            if (empty($interim->created_at)) {
                $interim->created_at = now();
            }
        });
    }

    public function pensionCase(): BelongsTo {
        return $this->belongsTo(PensionCase::class);
    }
}
