<?php

namespace App\Models;

use App\Enums\WithdrawStatusEnum;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;

class Withdraw extends Model
{
    public function getSearchAttribute()
    {
        return [
            'user.first_name',
            'user.last_name',
            'user.email',
            'status',
        ];
    }

    protected $guarded = ['id'];

    protected $casts = [
        'fields' => 'array',
        'status' => WithdrawStatusEnum::class,
    ];

    protected $appends = [
        'total',
        'converted_amount',
    ];

    public function total(): Attribute
    {
        return new Attribute(
            get: fn ($value) => $this->amount + $this->charge,
        );
    }

    public function convertedAmount(): Attribute
    {
        $defaultCurrency = Currency::getDefaultCurrency();

        return new Attribute(
            get: fn ($value) => convertCurrency($this->amount, $this->currency, $defaultCurrency?->code ?? 'USD'),
        );
    }

    public function isPending(): bool
    {
        return $this->status === WithdrawStatusEnum::PENDING;
    }

    public function user(): \Illuminate\Database\Eloquent\Relations\BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    public function withdrawMethod(): \Illuminate\Database\Eloquent\Relations\BelongsTo
    {
        return $this->belongsTo(WithdrawMethod::class);
    }

    public function transaction(): \Illuminate\Database\Eloquent\Relations\MorphOne
    {
        return $this->morphOne(Transaction::class, 'ref');
    }
}
