<?php

// app/Models/BalanceLog.php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Schema;

class BalanceLog extends Model
{
    protected $fillable = [
        'user_id',
        'amount',
        'type',
        'previous_balance',
        'new_balance',
    ];

    protected $casts = [
        'amount' => 'float',
        'previous_balance' => 'float',
        'new_balance' => 'float',
    ];

    protected static function booted(): void
    {
        static::creating(function (self $log): void {
            $log->fillBalanceSnapshot();
        });
    }

    private function fillBalanceSnapshot(): void
    {
        if (!self::supportsBalanceSnapshotColumns()) {
            return;
        }

        if ($this->user_id === null || $this->amount === null) {
            return;
        }

        if ($this->previous_balance !== null && $this->new_balance !== null) {
            return;
        }

        $currentBalance = User::query()
            ->whereKey((int) $this->user_id)
            ->value('balance');

        if ($currentBalance === null) {
            return;
        }

        $newBalance = round((float) $currentBalance, 2);
        $previousBalance = round($newBalance - (float) $this->amount, 2);

        if ($this->previous_balance === null) {
            $this->previous_balance = $previousBalance;
        }

        if ($this->new_balance === null) {
            $this->new_balance = $newBalance;
        }
    }

    private static function supportsBalanceSnapshotColumns(): bool
    {
        static $supported;

        if ($supported !== null) {
            return $supported;
        }

        try {
            $table = (new static())->getTable();
            $supported = Schema::hasTable($table)
                && Schema::hasColumn($table, 'previous_balance')
                && Schema::hasColumn($table, 'new_balance');
        } catch (\Throwable) {
            $supported = false;
        }

        return $supported;
    }
}
