<?php

declare(strict_types=1);

namespace App\Models;

use App\Services\Billing\CurrencyService;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Plan extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'slug',
        'description',
        'service_type',
        'price',
        'currency',
        'billing_cycle',
        'stripe_price_id',
        'stripe_product_id',
        'paypal_plan_id',
        'features',
        'provisioning_config',
        'stock_quantity',
        'status',
        'sort_order',
        'days_to_suspend',
        'days_to_terminate',
        'auto_suspend_enabled',
        'auto_terminate_enabled',
    ];

    protected function casts(): array
    {
        return [
            'price' => 'decimal:2',
            'features' => 'array',
            'provisioning_config' => 'array',
            'stock_quantity' => 'integer',
            'sort_order' => 'integer',
            'days_to_suspend' => 'integer',
            'days_to_terminate' => 'integer',
            'auto_suspend_enabled' => 'boolean',
            'auto_terminate_enabled' => 'boolean',
        ];
    }

    public function orders(): HasMany
    {
        return $this->hasMany(Order::class);
    }

    public function services(): HasMany
    {
        return $this->hasMany(Service::class);
    }

    public function prices(): HasMany
    {
        return $this->hasMany(PlanPrice::class);
    }

    public function configGroups(): BelongsToMany
    {
        return $this->belongsToMany(PlanConfigGroup::class, 'plan_config_group_plan');
    }

    public function priceForCycle(string $cycle): ?PlanPrice
    {
        return $this->prices()->where('billing_cycle', $cycle)->first();
    }

    public function isAvailable(): bool
    {
        if (! in_array($this->status, ['active', 'internal'])) {
            return false;
        }

        if ($this->stock_quantity !== null && $this->stock_quantity <= 0) {
            return false;
        }

        return true;
    }

    public function priceInCurrency(string $currency): float
    {
        if (strtoupper($currency) === strtoupper($this->currency ?? 'USD')) {
            return (float) $this->price;
        }

        /** @var CurrencyService $currencyService */
        $currencyService = app(CurrencyService::class);

        return $currencyService->convert((float) $this->price, $this->currency ?? 'USD', $currency);
    }

    public function scopePublic(Builder $query): Builder
    {
        return $query->whereNotIn('status', ['hidden', 'internal', 'inactive']);
    }
}
