<?php

namespace App\Models;

use App\Enums\PaymentTransactionStatus;
use App\Enums\PaymentTransactionType;
use Illuminate\Database\Eloquent\Concerns\HasUlids;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class PaymentTransaction extends Model
{
    /** @use HasFactory<\Database\Factories\PaymentTransactionFactory> */
    use HasFactory, HasUlids;

    protected $fillable = [
        'user_id',
        'credit_product_id',
        'credit_ledger_entry_id',
        'type',
        'status',
        'stripe_event_id',
        'stripe_event_type',
        'stripe_customer_id',
        'stripe_checkout_session_id',
        'stripe_invoice_id',
        'stripe_payment_intent_id',
        'stripe_subscription_id',
        'stripe_price_id',
        'amount',
        'currency',
        'credits_expected',
        'credits_granted',
        'invoice_url',
        'invoice_pdf_url',
        'invoice_email_sent_at',
        'error_message',
        'payload',
        'processed_at',
    ];

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

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

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

    protected function casts(): array
    {
        return [
            'type' => PaymentTransactionType::class,
            'status' => PaymentTransactionStatus::class,
            'amount' => 'integer',
            'credits_expected' => 'integer',
            'credits_granted' => 'integer',
            'invoice_email_sent_at' => 'datetime',
            'payload' => 'array',
            'processed_at' => 'datetime',
        ];
    }
}
