<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Str;
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable implements MustVerifyEmail
{
    use HasFactory;
    use Notifiable;
    use HasRoles;

    public $incrementing = false;

    protected $keyType = 'string';

    protected $fillable = [
        'public_id',
        'username',
        'email',
        'password',
        'status',
        'blocked_reason',
    ];

    protected $hidden = [
        'password',
        'remember_token',
    ];

    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
        ];
    }

    protected static function booted(): void
    {
        static::creating(function (self $user): void {
            if (empty($user->id)) {
                $user->id = (string) Str::uuid();
            }

            if (empty($user->public_id)) {
                $user->public_id = app(\App\Support\Security\PublicIdGenerator::class)->generateUserId();
            }
        });

        static::created(function (self $user): void {
            $user->wallet()->create([
                'currency' => 'USD',
                'available_balance' => 0,
                'held_balance' => 0,
                'can_send' => true,
                'can_receive' => true,
                'daily_send_limit' => 500000,
                'monthly_send_limit' => 5000000,
                'velocity_limit_per_minute' => 10,
            ]);

            $user->security()->create([
                'totp_enabled' => false,
            ]);

            $user->businessProfile()->create([
                'business_name' => null,
                'is_business_enabled' => false,
                'kyc_status' => 'pending',
            ]);
        });
    }

    public function wallet(): HasOne
    {
        return $this->hasOne(Wallet::class);
    }

    public function security(): HasOne
    {
        return $this->hasOne(UserSecurity::class);
    }

    public function businessProfile(): HasOne
    {
        return $this->hasOne(BusinessProfile::class);
    }

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

    public function sentTransfers(): HasMany
    {
        return $this->hasMany(Transfer::class, 'sender_user_id');
    }

    public function receivedTransfers(): HasMany
    {
        return $this->hasMany(Transfer::class, 'receiver_user_id');
    }
}
