<?php

namespace SoftminalB2B\Import;

if (!defined('ABSPATH')) {
    exit;
}

use SoftminalB2B\Http\Controllers\Controller;

/**
 * Admin REST for incumbent migration (`smb2b/v1/import`): detect sources,
 * preview a dry run, then commit.
 */
class ImportController extends Controller
{
    /**
     * @return array<int, SourceImporter>
     */
    private static function importers(): array
    {
        return [
            new B2BKingImporter(),
            new WholesaleSuiteImporter(),
            new WholesaleXImporter(),
        ];
    }

    private static function importer(string $slug): ?SourceImporter
    {
        foreach (self::importers() as $importer) {
            if ($importer->slug() === $slug) {
                return $importer;
            }
        }

        return null;
    }

    /**
     * Which incumbents have data available to import.
     */
    public function sources(\WP_REST_Request $request, $params = [])
    {
        $sources = [];

        foreach (self::importers() as $importer) {
            $sources[] = [
                'slug'    => $importer->slug(),
                'label'   => $importer->label(),
                'present' => $importer->isPresent(),
            ];
        }

        return $this->success(['sources' => $sources]);
    }

    public function preview(\WP_REST_Request $request, $params = [])
    {
        $importer = self::importer(sanitize_key((string) ($params['slug'] ?? '')));

        if (!$importer) {
            return $this->notFound(__('Unknown import source.', 'softminal-b2b-wholesale-for-woocommerce'));
        }

        return $this->success(['report' => $importer->preview()->toArray()]);
    }

    public function run(\WP_REST_Request $request, $params = [])
    {
        $importer = self::importer(sanitize_key((string) ($params['slug'] ?? '')));

        if (!$importer) {
            return $this->notFound(__('Unknown import source.', 'softminal-b2b-wholesale-for-woocommerce'));
        }

        return $this->success(
            ['report' => $importer->run()->toArray()],
            __('Import complete.', 'softminal-b2b-wholesale-for-woocommerce')
        );
    }
}
