<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class AppVersion extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'app_type',
        'version',
        'build_number',
        'min_version',
        'force_update',
        'release_notes',
        'download_url',
        'is_active',
    ];

    protected $casts = [
        'force_update' => 'boolean',
        'is_active' => 'boolean',
        'build_number' => 'integer',
    ];

    /**
     * Scope to get active versions only
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    /**
     * Scope to filter by app type
     */
    public function scopeOfType($query, $type)
    {
        return $query->where('app_type', $type);
    }

    /**
     * Get the latest active version for an app type
     */
    public static function getLatestVersion($appType)
    {
        return self::where('app_type', $appType)
            ->where('is_active', true)
            ->orderBy('build_number', 'desc')
            ->first();
    }

    /**
     * Check if an update is required
     */
    public function requiresUpdate($currentVersion, $currentBuild)
    {
        // Compare build numbers
        if ($this->build_number > $currentBuild) {
            return [
                'required' => true,
                'force' => $this->force_update,
                'version' => $this,
            ];
        }

        return [
            'required' => false,
            'force' => false,
            'version' => null,
        ];
    }
}
