<?php

namespace App\Models\Support;

use App\Models\Environments\Environment;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Support extends Model
{
    use HasFactory, SoftDeletes;

    const EXPIRED_DAYS = 30;

    const STATUS = [
        0 => 'Sin Soporte',
        1 => 'Sin fechas',
        2 => 'Sin comenzar',
        3 => 'Caducado',
        4 => 'Próximo a caducar',
        5 => 'Activado',
        6 => 'Desactivado',
    ];

    protected $fillable = [
        'name',
        'shortname',
        'description',
    ];

    protected $casts = [
        'description' => 'string',
    ];

    /**
     * Entornos que tienen este soporte
     */
    public function environments()
    {
        return $this->belongsToMany(Environment::class, 'environment_support')
            ->withPivot(['comment', 'start_at', 'end_at'])
            ->withTimestamps();
    }

    /* ============================================================
     |   LOGICA LEGACY (manteniéndola pero limpiando bordes)
     * ============================================================
     */

    /**
     * Determina el estado del soporte según fechas.
     */
    public static function get_status_support(Carbon $start, Carbon $end, $can_activate = true): int
    {
        $now = Carbon::now();
        $remaining = $end->diffInDays($now);

        // Si el fin está antes que ahora → remaining debe ser negativo
        if ($end < $now) {
            $remaining = -$remaining;
        }

        // Aún no ha comenzado
        if ($now < $start) {
            return 2;
        }

        // Próximo a caducar (< 30 días)
        if ($remaining > 0 && $remaining < self::EXPIRED_DAYS) {
            return 4;
        }

        // Caducado (hoy o ya pasado)
        if ($remaining < 1) {
            return 3;
        }

        // Activo / desactivado
        return $can_activate ? 5 : 6;
    }

    /**
     * Comprueba si una versión es más nueva que otra.
     */
    public static function has_updated(string $current, string $new): bool
    {
        $a = self::map_version(explode('.', $current));
        $b = self::map_version(explode('.', $new));

        return $b > $a;
    }

    /**
     * Convierte "4.3.2" en [4, 3, 2] para comparación.
     */
    public static function map_version(array $ver): array
    {
        return [
            (int) ($ver[0] ?? 0),
            (int) ($ver[1] ?? 0),
            (int) ($ver[2] ?? 0),
        ];
    }

    /**
     * Determina si el soporte está aún activo (útil en listados).
     */
    public static function is_enabled($environment_support): bool
    {
        if (!$environment_support?->start_at || !$environment_support?->end_at) {
            return false;
        }

        $start = Carbon::parse($environment_support->start_at);
        $end   = Carbon::parse($environment_support->end_at);

        return self::get_status_support($start, $end) < 4;
    }
}

