<?php

declare(strict_types=1);

namespace App\Administration\Domain\Model\Import;

use App\Administration\Domain\Exception\MappingIncompletException;

use function in_array;

/**
 * Value Object représentant l'association entre les colonnes du fichier source
 * et les champs Classeo.
 *
 * @see FR76: Import élèves via CSV
 */
final readonly class ColumnMapping
{
    /**
     * @param array<string, StudentImportField> $mapping Colonne source → champ Classeo
     */
    private function __construct(
        public array $mapping,
        public KnownImportFormat $format,
    ) {
    }

    /**
     * @param array<string, StudentImportField> $mapping Colonne source → champ Classeo
     */
    public static function creer(array $mapping, KnownImportFormat $format): self
    {
        $mappedFields = array_values($mapping);
        $champsObligatoires = StudentImportField::champsObligatoires();
        $hasFullName = in_array(StudentImportField::FULL_NAME, $mappedFields, true);

        foreach ($champsObligatoires as $champ) {
            if ($hasFullName && ($champ === StudentImportField::LAST_NAME || $champ === StudentImportField::FIRST_NAME)) {
                continue;
            }
            if (!in_array($champ, $mappedFields, true)) {
                throw MappingIncompletException::champManquant($champ);
            }
        }

        return new self($mapping, $format);
    }

    public function champPour(string $colonneSource): ?StudentImportField
    {
        return $this->mapping[$colonneSource] ?? null;
    }

    /**
     * @return list<string>
     */
    public function colonnesSources(): array
    {
        return array_keys($this->mapping);
    }

    public function equals(self $other): bool
    {
        return $this->mapping === $other->mapping && $this->format === $other->format;
    }
}
