<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

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

    protected $fillable = [
        'name',
        'sort',
        'plan_key',
        'price',
        'yearly_discount_months',
        'is_featured',
        'credit_limit',
        'device_limit',
        'active',
        'is_internal',
        'ai_config',
    ];

    protected $casts = [
        'active' => 'boolean',
        'is_featured' => 'boolean',
        'is_internal' => 'boolean',
        'ai_config' => 'array',
    ];

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

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

    // RELATION
    public function subscriptions()
    {
        return $this->hasMany(Subscription::class);
    }


    public function features()
    {
        return $this->belongsToMany(
            \App\Models\Feature::class,
            'feature_plan',
            'plan_id',
            'feature_id'
        )->withTimestamps(false);
    }

    public function getAiModel(): string
    {
        return $this->ai_config['model']
            ?? $this->ai_model
            ?? 'gpt-4o-mini';
    }

    public function isFree(): bool
    {
        return $this->price === 0 || $this->price === null;
    }

    public function scopePublic($query)
    {
        return $query->where(function ($q) {
            $q->where('is_internal', false)->orWhereNull('is_internal');
        });
    }

    public static function freePlan(): ?self
    {
        return static::public()
            ->where(function ($q) {
                $q->where('price', 0)->orWhereNull('price');
            })
            ->first();
    }

    public function getMonthlyPrice()
    {
        return $this->price;
    }

    public function getYearlyPrice()
    {
        $months = 12 - $this->yearly_discount_months;
        return $this->price * $months;
    }

}
