<?php

namespace App\Models;

use Illuminate\Support\Str;
use Illuminate\Database\Eloquent\Model;

class UserBalance extends Model
{
    protected $guarded = [];

    protected $casts = [];

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            if (empty($model->uuid)) {
                $model->uuid = (string) Str::uuid();
            }
        });
    }

    /**
     * Get the user that owns this balance
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    /**
     * Get the market for this balance
     */
    public function market()
    {
        return $this->belongsTo(Market::class);
    }

    /**
     * Increment balance
     */
    public function addBalance(float $amount): self
    {
        $this->increment('balance', $amount);
        return $this;
    }

    /**
     * Decrement balance
     */
    public function deductBalance(float $amount): self
    {
        $this->decrement('balance', $amount);
        return $this;
    }

    /**
     * Check if balance is sufficient
     */
    public function hasSufficientBalance(float $amount): bool
    {
        return $this->balance >= $amount;
    }
}
