<?php

namespace App\Apps\Versionmgr\Models;

use App\Models\BaseModel;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class SystemVersion extends BaseModel
{
    protected $table = 'app_versionmgr_system_version';

    public const CREATED_AT = 'create_time';

    public const UPDATED_AT = 'update_time';

    protected $fillable = [
        'version',
        'build',
        'changelog',
        'upgrade_type',
        'status',
        'operator_id',
        'backup_path',
        'upgrade_result',
        'error_message',
        'detail',
    ];

    protected $casts = [
        'status' => 'integer',
        'upgrade_result' => 'integer',
        'detail' => 'array',
    ];

    public function operator(): BelongsTo
    {
        return $this->belongsTo(\App\Models\AdminUser::class, 'operator_id');
    }

    public static function getCurrentVersion(): ?self
    {
        return static::where('status', 1)->orderBy('id', 'desc')->first();
    }

    public static function getCurrentVersionString(): string
    {
        $record = static::getCurrentVersion();
        return $record ? $record->version : config('app.version', '5.0.1');
    }
}
