<?php

namespace App\Models;

use App\Enums\CreditProductType;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Concerns\HasUlids;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

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

    protected $fillable = [
        'name',
        'description',
        'type',
        'credits',
        'amount',
        'currency',
        'stripe_product_id',
        'stripe_price_id',
        'is_active',
        'sort_order',
    ];

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

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

    public function scopeActive(Builder $query): Builder
    {
        return $query->where('is_active', true);
    }

    public function formattedAmount(): string
    {
        return number_format($this->amount / 100, 2, ',', ' ').' '.strtoupper($this->currency);
    }

    protected function casts(): array
    {
        return [
            'type' => CreditProductType::class,
            'credits' => 'integer',
            'amount' => 'integer',
            'is_active' => 'boolean',
            'sort_order' => 'integer',
        ];
    }
}
