<?php

declare(strict_types=1);

namespace Plugins\Larablog\Membership\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Plugins\Larablog\Payment\Domain\ProductType;
use Plugins\Larablog\Payment\Models\Entitlement;

class MembershipPlan extends Model
{
    protected $fillable = [
        'slug',
        'name',
        'description',
        'price',
        'currency',
        'duration_days',
        'enabled',
        'sort_order',
    ];

    protected function casts(): array
    {
        return [
            'price' => 'decimal:2',
            'duration_days' => 'integer',
            'enabled' => 'boolean',
            'sort_order' => 'integer',
        ];
    }

    public function articleGates(): HasMany
    {
        return $this->hasMany(ArticleMembership::class, 'required_plan_id');
    }

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

    public function isLifetime(): bool
    {
        return $this->duration_days === null;
    }

    public function hasEntitlements(): bool
    {
        return Entitlement::query()
            ->where('product_type', ProductType::MEMBERSHIP)
            ->where('product_id', $this->id)
            ->exists();
    }
}
