<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class MeterReading extends Model
{
    protected $fillable = [
        'lease_id', 'month', 'previous_reading', 'current_reading',
        'units_consumed', 'rate_per_unit', 'total_amount',
    ];

    protected $casts = [
        'previous_reading' => 'decimal:2',
        'current_reading' => 'decimal:2',
        'units_consumed' => 'decimal:2',
        'rate_per_unit' => 'decimal:2',
        'total_amount' => 'decimal:2',
    ];

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

    protected static function booted(): void
    {
        static::creating(function (MeterReading $reading) {
            $reading->units_consumed = $reading->current_reading - $reading->previous_reading;
            $reading->total_amount = $reading->units_consumed * $reading->rate_per_unit;
        });
    }
}
