<?php

namespace App\Models;

use App\IntegrationRepository;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Facades\App;
use Mtc\MercuryDataModels\Factories\ImportConditionFactory;

class ImportCondition extends Model
{
    use HasFactory;

    protected $fillable = [
        'provider',
        'import_map_id',
        'active',
        'do_not_import',
        'do_not_publish',
        'data',
    ];

    protected $casts = [
        'active' => 'boolean',
        'data' => 'array',
    ];

    protected $appends = [
        'name',
    ];

    protected static function newFactory()
    {
        return ImportConditionFactory::new();
    }

    public function rules(): HasMany
    {
        return $this->hasMany(ImportConditionRule::class);
    }

    public function importMap(): BelongsTo
    {
        return $this->belongsTo(ImportMap::class);
    }

    public function getNameAttribute(): string
    {
        if (empty($this->attributes['provider'])) {
            return __('integrations.condition_applies_to_all');
        }

        if (!empty($this->attributes['import_map_id'])) {
            return __('integrations.condition_applies_to_import_map', [
                'import_map' => $this->importMap?->name,
            ]);
        }

        return __('integrations.condition_applies_to_provider', [
            'provider' => $this->getProviderName(),
        ]);
    }

    public function getProviderName(): string
    {
        $providers = (new IntegrationRepository())->getEnabledForType('stock');
        $class = $providers[$this->provider]['class'] ?? null;
        return $class ? App::make($class)->name() : '';
    }
}
