<?php

namespace App\Models\Vouchers;

use App\Models\Concerns\BelongsToTenant;
use App\Models\Customers\Customer;
use App\Models\Sales\Invoice;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Str;

class VoucherRedemption extends Model
{
    use BelongsToTenant;

    protected $fillable = [
        'uuid', 'voucher_id', 'invoice_id', 'customer_id', 'redeemed_amount',
        'balance_before', 'balance_after', 'redeemed_by', 'redeemed_at',
        'is_reversed', 'reversed_at', 'reversed_by', 'reverse_reason',
    ];

    protected function casts(): array
    {
        return [
            'redeemed_amount' => 'decimal:2',
            'balance_before' => 'decimal:2',
            'balance_after' => 'decimal:2',
            'redeemed_at' => 'datetime',
            'is_reversed' => 'boolean',
            'reversed_at' => 'datetime',
        ];
    }

    protected static function booted(): void
    {
        static::creating(function (self $redemption): void {
            if (! $redemption->uuid) {
                $redemption->uuid = (string) Str::ulid();
            }
        });
    }

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

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

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

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