<?php

namespace App\Models;

use App\Enums\SubscriptionStatus;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class Subscription extends Model
{
    protected $keyType = 'string';
    public $incrementing = false;

    protected $fillable = [
        'user_id',
        'plan_id',

        'plan_name',
        'plan_slug',

        'price',
        'original_price',
        'discount_amount',

        'interval',
        'status',

        'starts_at',
        'ends_at',

        'provider',
        'provider_customer_id',
        'provider_subscription_id',

        'gifted_by',
        'gifted_at',
        'gift_reason',
    ];

    protected $casts = [
        'starts_at'  => 'datetime',
        'ends_at'    => 'datetime',
        'gifted_at'  => 'datetime',
        'status'     => SubscriptionStatus::class,
    ];

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

        static::creating(function ($model) {
            if (!$model->id) {
                $model->id = (string) Str::uuid();
            }
        });
    }

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

    public function plan()
    {
        return $this->belongsTo(Plan::class);
    }

    public function payments()
    {
        return $this->hasMany(Payment::class);
    }

    public function gifter()
    {
        return $this->belongsTo(User::class, 'gifted_by');
    }

    // HELPER
    public function isActive()
    {
        return in_array($this->status->value, ['active', 'gifted'])
            && (!$this->ends_at || $this->ends_at->isFuture());
    }

    public function isGifted(): bool
    {
        return $this->status === SubscriptionStatus::Gifted;
    }
}
