using MediatR;
using SolutionErp.Application.Common.Interfaces;
using SolutionErp.Application.Master.Suppliers.Dtos;
using SolutionErp.Application.Master.Suppliers.Import;

namespace SolutionErp.Application.Master.Suppliers.Commands.ImportSuppliers;

/// <summary>
/// Commit các hàng đã preview (ALL-OR-NOTHING). Body JSON = { "rows": [ ... ] }.
/// Actor resolve từ ICurrentUser (chỉ để log — audit CreatedBy/UpdatedBy do interceptor set).
/// </summary>
public sealed record SupplierImportConfirmCommand(IReadOnlyList<SupplierImportRowDto> Rows)
    : IRequest<SupplierImportResultDto>;

public sealed class SupplierImportConfirmCommandHandler(
    ISupplierExcelImportService importService,
    ICurrentUser currentUser)
    : IRequestHandler<SupplierImportConfirmCommand, SupplierImportResultDto>
{
    public Task<SupplierImportResultDto> Handle(SupplierImportConfirmCommand request, CancellationToken ct)
    {
        var actor = currentUser.FullName
                    ?? currentUser.Email
                    ?? currentUser.UserId?.ToString()
                    ?? "unknown";
        return importService.ConfirmAsync(request.Rows ?? Array.Empty<SupplierImportRowDto>(), actor, ct);
    }
}
