<?php

namespace App\Models;

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

class PackagePurchase extends Model
{
    use HasFactory;

    protected $table = 'package_purchases';

    protected $fillable = [
        'tenant_id',
        'event_id',
        'package_id',
        'provider',
        'provider_id',
        'price',
        'type',
        'metadata',
        'ip_address',
        'user_agent',
        'refunded',
        'purchased_at',
    ];

    protected $casts = [
        'price' => 'decimal:2',
        'purchased_at' => 'datetime',
        'metadata' => 'array',
        'refunded' => 'boolean',
    ];

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

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

    public function package(): BelongsTo
    {
        return $this->belongsTo(Package::class)->withTrashed();
    }

    public function isEndcustomerEvent(): bool
    {
        return $this->type === 'endcustomer_event';
    }

    public function isResellerSubscription(): bool
    {
        return $this->type === 'reseller_subscription';
    }

    public function isRefunded(): bool
    {
        return $this->refunded;
    }

    public function getMetadataAttribute($value)
    {
        return $value ? json_decode($value, true) : [];
    }

    public function setMetadataAttribute($value)
    {
        $this->attributes['metadata'] = is_array($value) ? json_encode($value) : $value;
    }

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($purchase) {
            if (! $purchase->tenant_id) {
                throw new \Exception('Tenant ID is required for package purchases.');
            }

            if (! $purchase->purchased_at) {
                $purchase->purchased_at = now();
            }
            $purchase->refunded = false;
        });
    }
}
