<?php

namespace App\Models;

use App\Models\Concerns\BelongsToTenant;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\MorphTo;

class CommunicationUnitTransaction extends Model
{
    use BelongsToTenant;

    public const TYPE_TOPUP = 'topup';
    public const TYPE_USAGE = 'usage';
    public const TYPE_REFUND = 'refund';

    public const DIRECTION_CREDIT = 'credit';
    public const DIRECTION_DEBIT = 'debit';

    public const PAYER_MEMBER = 'member';
    public const PAYER_TENANT = 'tenant';

    protected $fillable = [
        'tenant_id',
        'communication_unit_wallet_id',
        'communication_unit_topup_id',
        'customer_id',
        'savings_transaction_id',
        'notification_campaign_id',
        'created_by',
        'channel',
        'type',
        'direction',
        'units',
        'unit_price',
        'amount',
        'cost_amount',
        'balance_before',
        'balance_after',
        'payer_type',
        'reference',
        'description',
        'related_type',
        'related_id',
        'metadata',
    ];

    protected function casts(): array
    {
        return [
            'units' => 'integer',
            'unit_price' => 'decimal:2',
            'amount' => 'decimal:2',
            'cost_amount' => 'decimal:2',
            'balance_before' => 'integer',
            'balance_after' => 'integer',
            'metadata' => 'array',
        ];
    }

    public function wallet(): BelongsTo
    {
        return $this->belongsTo(CommunicationUnitWallet::class, 'communication_unit_wallet_id');
    }

    public function topup(): BelongsTo
    {
        return $this->belongsTo(CommunicationUnitTopup::class, 'communication_unit_topup_id');
    }

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

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

    public function campaign(): BelongsTo
    {
        return $this->belongsTo(NotificationCampaign::class, 'notification_campaign_id');
    }

    public function creator(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    public function related(): MorphTo
    {
        return $this->morphTo();
    }

    public function channelLabel(): string
    {
        return CommunicationUnitWallet::channels()[$this->channel] ?? str($this->channel)->headline()->toString();
    }
}
