<?php

declare(strict_types=1);

namespace App\Models;

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

class BankCard extends Model
{
    protected $guarded = ['id', 'created_at', 'updated_at'];

    protected $casts = [
        'is_default' => 'boolean',
        'meta' => 'array',
    ];

    public const STATUS_ACTIVE = 'active';
    public const STATUS_INACTIVE = 'inactive';

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

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

    public function maskedCardNumber(): ?string
    {
        if (! $this->card_number) {
            return null;
        }

        $digits = preg_replace('/\D+/', '', $this->card_number) ?: '';
        if (strlen($digits) < 8) {
            return $this->card_number;
        }

        return substr($digits, 0, 4) . '-****-****-' . substr($digits, -4);
    }

    public function markAsDefault(): void
    {
        static::query()
            ->where('user_id', $this->user_id)
            ->where('id', '!=', $this->id)
            ->update(['is_default' => false]);

        $this->update(['is_default' => true, 'status' => self::STATUS_ACTIVE]);
    }
}
