<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class ExpenseRefundBatch extends Model
{
    use HasFactory;

    protected $fillable = [
        'organisation_id',
        'bulk_reference',
        'expense_approval_ids',
        'transactions_payload',
        'total_amount',
        'transaction_count',
        'status',
        'expires_at',
    ];

    protected $casts = [
        'expense_approval_ids' => 'array',
        'transactions_payload' => 'array',
        'total_amount'         => 'decimal:2',
        'expires_at'           => 'datetime',
    ];

    public function organisation()
    {
        return $this->belongsTo(Organisation::class);
    }

    public function expenseTransactions()
    {
        return $this->hasMany(ExpenseTransaction::class, 'bulk_reference', 'bulk_reference');
    }

    public function expenseApprovals()
    {
        return $this->hasMany(ExpenseApproval::class, 'id', 'expense_approval_ids');
    }

    /**
     * Check if the batch reference is still valid (not expired)
     */
    public function isValid(): bool
    {
        return $this->expires_at && now()->lessThan($this->expires_at)
            && !in_array($this->status, ['COMPLETED', 'FAILED']);
    }
}
