<?php

namespace SoftminalB2B\Import;

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

/**
 * Accumulates what an import did (or would do, in a dry run) so the admin sees
 * an honest preview before committing and a summary after: counts per entity,
 * plus every warning about something that could not be mapped cleanly (H8
 * acceptance — "report of anything unmappable").
 */
class ImportReport
{
    public bool $committed = false;

    /** @var array<string, array{created:int, updated:int, skipped:int}> */
    private array $entities = [];

    /** @var array<int, string> */
    private array $warnings = [];

    /**
     * High-impact changes the merchant should know happened — not failures, but
     * things that visibly change the storefront (e.g. the whole catalogue going
     * private). Shown prominently, above the "couldn't migrate" warnings.
     *
     * @var array<int, string>
     */
    private array $notices = [];

    public function created(string $entity): void
    {
        $this->bump($entity, 'created');
    }

    public function updated(string $entity): void
    {
        $this->bump($entity, 'updated');
    }

    public function skipped(string $entity): void
    {
        $this->bump($entity, 'skipped');
    }

    public function warn(string $message): void
    {
        $this->warnings[] = $message;
    }

    public function notice(string $message): void
    {
        // De-dupe: the same high-impact change (e.g. catalogue went private) can
        // be triggered by more than one source rule.
        if (!in_array($message, $this->notices, true)) {
            $this->notices[] = $message;
        }
    }

    private function bump(string $entity, string $key): void
    {
        if (!isset($this->entities[$entity])) {
            $this->entities[$entity] = ['created' => 0, 'updated' => 0, 'skipped' => 0];
        }

        $this->entities[$entity][$key]++;
    }

    /**
     * @return array<string, mixed>
     */
    public function toArray(): array
    {
        return [
            'committed' => $this->committed,
            'entities'  => $this->entities,
            'notices'   => $this->notices,
            'warnings'  => $this->warnings,
        ];
    }
}
