package de.effigenix.application.masterdata.supplier;

import de.effigenix.application.masterdata.supplier.command.UpdateSupplierCommand;
import de.effigenix.domain.masterdata.supplier.*;
import de.effigenix.shared.common.Result;
import de.effigenix.shared.persistence.UnitOfWork;
import de.effigenix.shared.security.ActorId;

public class UpdateSupplier {

    private final SupplierRepository supplierRepository;
    private final UnitOfWork unitOfWork;

    public UpdateSupplier(SupplierRepository supplierRepository, UnitOfWork unitOfWork) {
        this.supplierRepository = supplierRepository;
        this.unitOfWork = unitOfWork;
    }

    public Result<SupplierError, Supplier> execute(UpdateSupplierCommand cmd, ActorId performedBy) {
        // 1. Laden
        var supplierId = SupplierId.of(cmd.supplierId());

        Supplier supplier;
        switch (supplierRepository.findById(supplierId)) {
            case Result.Failure(var err) ->
                { return Result.failure(new SupplierError.RepositoryFailure(err.message())); }
            case Result.Success(var opt) -> {
                if (opt.isEmpty()) {
                    return Result.failure(new SupplierError.SupplierNotFound(supplierId));
                }
                supplier = opt.get();
            }
        }

        // 2. Draft bauen + Aggregate delegiert Validierung
        var draft = new SupplierUpdateDraft(
                cmd.name(), cmd.phone(), cmd.email(), cmd.contactPerson(),
                cmd.street(), cmd.houseNumber(), cmd.postalCode(), cmd.city(), cmd.country(),
                cmd.paymentDueDays(), cmd.paymentDescription()
        );
        switch (supplier.update(draft)) {
            case Result.Failure(var err) -> { return Result.failure(err); }
            case Result.Success(var ignored) -> { }
        }

        // 3. Speichern
        return unitOfWork.executeAtomically(() -> {
            switch (supplierRepository.save(supplier)) {
                case Result.Failure(var err) ->
                    { return Result.failure(new SupplierError.RepositoryFailure(err.message())); }
                case Result.Success(var ignored) -> { }
            }
            return Result.success(supplier);
        });
    }
}
