<?php

namespace App\Models;

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

class Payment extends Model
{
    /** @use HasFactory<PaymentFactory> */
    use HasFactory;

    public const STATUS_CREATED = 'created';

    public const STATUS_AUTHORIZED = 'authorized';

    public const STATUS_CAPTURED = 'captured';

    public const STATUS_FAILED = 'failed';

    /**
     * The attributes that are mass assignable.
     *
     * @var list<string>
     */
    protected $fillable = [
        'user_id',
        'provider',
        'razorpay_order_id',
        'razorpay_payment_id',
        'razorpay_signature',
        'amount_paise',
        'currency',
        'status',
        'order_payload',
        'payment_payload',
        'webhook_payload',
        'verified_at',
        'failed_at',
        'unlocked_at',
    ];

    /**
     * @return BelongsTo<User, $this>
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    public function isVerified(): bool
    {
        return $this->verified_at !== null;
    }

    public function unlocksAccess(): bool
    {
        return $this->unlocked_at !== null;
    }

    public function formattedAmount(): string
    {
        $currency = strtoupper($this->currency ?: 'INR');
        $amount = number_format($this->amount_paise / 100, 2);

        return "{$currency} {$amount}";
    }

    /**
     * Get the attributes that should be cast.
     *
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'amount_paise' => 'integer',
            'order_payload' => 'array',
            'payment_payload' => 'array',
            'webhook_payload' => 'array',
            'verified_at' => 'datetime',
            'failed_at' => 'datetime',
            'unlocked_at' => 'datetime',
        ];
    }
}
