<?php

namespace App\Models;

use App\Enums\TransactionStatus;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Transaction extends Model
{
    protected $fillable = [
        'user_id',
        'gateway',
        'transaction_id',
        'amount',
        'currency',
        'status',
        'payment_method',
        'response_json',
        'idempotency_key',
        'metadata',
    ];

    protected function casts(): array
    {
        return [
            'amount' => 'decimal:2',
            'response_json' => 'array',
            'metadata' => 'array',
        ];
    }

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

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

    public function statusEnum(): ?TransactionStatus
    {
        return TransactionStatus::tryFrom($this->status);
    }

    public function isSuccessful(): bool
    {
        return $this->status === TransactionStatus::Succeeded->value;
    }
}
