<?php

namespace App\Models;

use App\Enums\AppStatus;
use Illuminate\Database\Eloquent\Builder;
use App\Models\BaseModel;
use Illuminate\Database\Eloquent\Relations\HasMany;

class AppModel extends BaseModel
{
    protected $table = 'apps';

    public const CREATED_AT = 'create_time';

    public const UPDATED_AT = 'update_time';

    protected $fillable = [
        'app_id',
        'name',
        'description',
        'version',
        'author',
        'icon',
        'path',
        'status',
        'is_system',
        'manifest',
        'install_time',
    ];

    protected $casts = [
        'status' => AppStatus::class,
        'is_system' => 'boolean',
        'manifest' => 'array',
        'install_time' => 'datetime',
    ];

    public function dependencies(): HasMany
    {
        return $this->hasMany(AppDependency::class, 'app_id', 'app_id');
    }

    public function operationLogs(): HasMany
    {
        return $this->hasMany(AppOperationLog::class, 'app_id', 'app_id');
    }

    public function scopeEnabled(Builder $query): Builder
    {
        return $query->where('status', AppStatus::ENABLED);
    }

    public function scopeInstalled(Builder $query): Builder
    {
        return $query->whereIn('status', [
            AppStatus::INSTALLED,
            AppStatus::ENABLED,
            AppStatus::DISABLED,
        ]);
    }
}
