<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class Update extends Model
{
    protected $fillable = [
        'version',
        'type',
        'title',
        'description',
        'changelog',
        'download_url',
        'release_notes_url',
        'is_available',
        'requires_license',
        'released_at',
        'checked_at',
        'is_installed',
        'installed_at',
        'installed_by',
    ];

    protected function casts(): array
    {
        return [
            'is_available' => 'boolean',
            'requires_license' => 'boolean',
            'is_installed' => 'boolean',
            'released_at' => 'datetime',
            'checked_at' => 'datetime',
            'installed_at' => 'datetime',
        ];
    }

    public function installer(): BelongsTo
    {
        return $this->belongsTo(User::class, 'installed_by');
    }

    /**
     * Check if update is newer than current version
     */
    public function isNewerThan(string $currentVersion): bool
    {
        return version_compare($this->version, $currentVersion, '>');
    }

    /**
     * Get update type badge color
     */
    public function getTypeColor(): string
    {
        return match ($this->type) {
            'major' => 'bg-red-100 text-red-700',
            'minor' => 'bg-yellow-100 text-yellow-700',
            'patch' => 'bg-blue-100 text-blue-700',
            default => 'bg-gray-100 text-gray-700',
        };
    }
}
