<?php

namespace App\Console\Commands;

use App\Contracts\SalesChannel;
use App\IntegrationRepository;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\App;
use Mtc\MercuryDataModels\Tenant;

class SalesChannelExportCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'sales-channels:export';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Run sales channel scheduled exports for a global or tenant';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        if (tenant()) {
            $this->getIntegrations()
                ->each(function (SalesChannel $channel) {
                    $this->info('Running ' . $channel->name());
                    $channel->runScheduledExport();
                });
        } else {
            $integrations = collect();

            Tenant::all()->each(function ($tenant) use (&$integrations) {
                tenancy()->initialize($tenant);
                $integrations = $integrations->merge($this->getIntegrations(true));
            });

            $integrations->each(function (SalesChannel $channel) {
                $this->info('Running ' . $channel->name());
                $channel->runScheduledExport();
            });
        }

        return Command::SUCCESS;
    }

    private function getIntegrations($global = false)
    {
        return (new IntegrationRepository())
            ->getEnabledForType('sales-channels')
            ->filter(fn($integration) => !empty($integration['class']))
            ->filter(fn($integration) => $global
                ? ($integration['global'] ?? false)
                : !($integration['global'] ?? false))
            ->map(fn($integration) => App::make($integration['class']));
    }
}
