using Npgsql;

namespace Shared.Excel;

public interface IImportDefinition
{
    ImportDefinition Definition { get; }

    Task<IReadOnlyList<ImportRowValidation>> ValidateAsync(
        IReadOnlyList<ImportRawRow> rows,
        IReadOnlyDictionary<string, string> targetToSource,
        NpgsqlConnection connection,
        CancellationToken ct);

    /// <summary>
    /// Commit valid staged rows. Implementations own domain grouping and transaction boundaries.
    /// They must be idempotent for a session retry.
    /// </summary>
    Task<ImportCommitResult> CommitAsync(Guid sessionId, string actor, CancellationToken ct);
}

public sealed class ImportDefinitionRegistry(IEnumerable<IImportDefinition> definitions)
{
    private readonly IReadOnlyDictionary<string, IImportDefinition> _definitions =
        definitions.ToDictionary(x => x.Definition.Id, StringComparer.OrdinalIgnoreCase);

    public IImportDefinition Get(string importType) =>
        _definitions.TryGetValue(importType, out var value)
            ? value
            : throw new KeyNotFoundException($"Unknown import type: {importType}");

    public bool TryGet(string importType, out IImportDefinition? definition) =>
        _definitions.TryGetValue(importType, out definition);
}
