<?php

namespace App\Models;

use App\Enums\StatusEnum;
use App\Models\Core\File;
use App\Traits\Filterable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphOne;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;

class Platform extends Model
{
    use HasFactory, Filterable;

    protected $fillable = [
        'name',
        'slug',
        'url',
        'icon',
        'configuration',
        'status',
        'is_feature',
        'is_integrated',
        'view_option',
        'unofficial',
    ];

    protected $casts = [
        'configuration' => 'object',
    ];

    protected static function booted()
    {


        static::addGlobalScope('autoload', function (Builder $builder) {
            $builder->with(['file']);
        });

        static::creating(function (Model $model) {

            $model->uid = Str::uuid();
            $model->status = StatusEnum::true->status();
        });

        static::saving(function (Model $model) {
            if (request()->input('name')) {
                $model->slug = make_slug(request()->input('name'));
            }
        });

        static::saved(function (Model $model) {
            Cache::forget('platform');
        });

    }

    public function file(): MorphOne
    {
        return $this->morphOne(File::class, 'fileable');
    }

    public function fileUsages()
    {
        return $this->hasMany(UserFilePlatform::class);
    }


    public function scopeActive(Builder $q): Builder
    {
        return $q->where("status", StatusEnum::true->status());
    }

    public function scopeFeature(Builder $q): Builder
    {
        return $q->where("is_feature", StatusEnum::true->status());
    }

    public function scopeIntegrated(Builder $q): Builder
    {
        return $q->where("is_integrated", StatusEnum::true->status());
    }



    /**
     * Get all of social accounts
     *
     * @return HasMany
     */
    public function accounts(): HasMany
    {
        return $this->hasMany(SocialAccount::class, 'platform_id');
    }
}
