<?php

namespace App\Models;

use App\Enums\AccountStatus;
use App\Enums\AccountType;
use App\Enums\Currency;
use App\Enums\RoutingNumberType;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Account extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'account_number',
        'account_type',
        'currency',
        'balance',
        'status',
    ];

    protected function casts(): array
    {
        return [
            'account_type' => AccountType::class,
            'currency' => Currency::class,
            'status' => AccountStatus::class,
            'balance' => 'decimal:2',
        ];
    }

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

    public function transactions(): HasMany
    {
        return $this->hasMany(Transaction::class);
    }

    public function routingNumbers(): HasMany
    {
        return $this->hasMany(RoutingNumber::class);
    }

    public function holdings(): HasMany
    {
        return $this->hasMany(BrokerageHolding::class);
    }

    public function ensureRoutingNumbers(): void
    {
        foreach (RoutingNumberType::cases() as $type) {
            $this->routingNumbers()->firstOrCreate(
                ['type' => $type->value],
                ['routing_number' => RoutingNumber::generateRoutingNumber()]
            );
        }
    }

    protected static function booted(): void
    {
        static::created(function (Account $account) {
            $account->ensureRoutingNumbers();
        });
    }

    public static function generateAccountNumber(): string
    {
        do {
            $number = str_pad(random_int(0, 9999999999), 10, '0', STR_PAD_LEFT);
        } while (static::where('account_number', $number)->exists());

        return $number;
    }
}
