<?php

namespace App\Traits;

use App\IntegrationRepository;
use App\Models\ExportMap;
use App\Models\ExportMapTemplate;
use Illuminate\Support\Facades\App;

trait ChecksForExportMap
{
    /**
     * Checks if there is an active and configured ExportMap
     * for this specific sales channel.
     *
     * @return bool
     */
    protected function hasActiveExportMap(): bool
    {
        $activeTemplateIds = ExportMap::query()
            ->where('active', true)
            ->where('ftp_export_enabled', true)
            ->whereNotNull('template_id')
            ->pluck('template_id')
            ->unique();

        if ($activeTemplateIds->isEmpty()) {
            return false;
        }

        return ExportMapTemplate::query()
            ->whereIn('id', $activeTemplateIds)
            ->where('sales_channel', $this->getSalesChannelIntegrationKey())
            ->exists();
    }

    protected function getSalesChannelIntegrationKey(): string
    {
        return (string) App::make(IntegrationRepository::class)
            ->getEnabledForType('sales-channels')
            ->search(fn($integration) => ($integration['class'] ?? null) === self::class);
    }
}
