<?php

namespace App\Models;

use App\Core\Traits\HasUuid;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\SoftDeletes;

class Transaction extends Model
{
    use HasUuid, HasFactory, SoftDeletes;

    protected $fillable = [
        'user_id',
        'wallet_id',
        'bill_service_id',
        'bill_variation_id',
        'reference',
        'provider_reference',
        'receipt_number',
        'type',
        'service_name',
        'provider',
        'network',
        'customer_number',
        'customer_name',
        'customer_email',
        'amount',
        'fee',
        'total_amount',
        'cashback',
        'wallet_balance_before',
        'wallet_balance_after',
        'status',
        'provider_response',
        'provider_request',
        'token_data',
        'ip_address',
        'device',
        'description',
        'failure_reason',
        'idempotency_key',
        'processed_at',
        'completed_at',
    ];

    protected function casts(): array
    {
        return [
            'amount' => 'decimal:2',
            'fee' => 'decimal:2',
            'total_amount' => 'decimal:2',
            'cashback' => 'decimal:2',
            'wallet_balance_before' => 'decimal:2',
            'wallet_balance_after' => 'decimal:2',
            'provider_response' => 'array',
            'provider_request' => 'array',
            'token_data' => 'array',
            'processed_at' => 'datetime',
            'completed_at' => 'datetime',
        ];
    }

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

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

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

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

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

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

    public function isSuccessful(): bool
    {
        return $this->status === 'successful';
    }

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

    public function isFailed(): bool
    {
        return $this->status === 'failed';
    }

    public function isRefunded(): bool
    {
        return $this->status === 'refunded';
    }

    public function canBeRefunded(): bool
    {
        return in_array($this->status, ['successful', 'processing']);
    }
}
