<?php

declare(strict_types=1);

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;

final class OwnerPaymentAccount extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'owner_id',
        'type',
        'account_name',
        'is_primary',
        'details',
        'notes',
    ];

    protected function casts(): array
    {
        return [
            'is_primary' => 'boolean',
            'details' => 'array',
        ];
    }

    public function owner(): BelongsTo
    {
        return $this->belongsTo(User::class, 'owner_id');
    }

    public function scopePrimary($query)
    {
        return $query->where('is_primary', true);
    }

    public function scopeForOwner($query, int $ownerId)
    {
        return $query->where('owner_id', $ownerId);
    }

    public function scopeByType($query, string $type)
    {
        return $query->where('type', $type);
    }

    public function getBankDetails(): ?array
    {
        return $this->type === 'bank_transfer' ? $this->details : null;
    }

    public function getCryptoDetails(): ?array
    {
        return $this->type === 'crypto' ? $this->details : null;
    }

    public function getPayPalEmail(): ?string
    {
        return $this->type === 'paypal' ? $this->details['email'] ?? null : null;
    }

    public function getDisplayDetails(): string
    {
        return match ($this->type) {
            'bank_transfer' => $this->details['bank_name'].' - '.substr($this->details['account_number'], -4),
            'crypto' => $this->details['currency'].' - '.substr($this->details['wallet_address'], 0, 8).'...',
            'paypal' => $this->details['email'],
            default => 'Unknown',
        };
    }
}
