package de.effigenix.application.masterdata.supplier;

import de.effigenix.application.masterdata.supplier.command.CreateSupplierCommand;
import de.effigenix.domain.masterdata.supplier.Supplier;
import de.effigenix.domain.masterdata.supplier.SupplierDraft;
import de.effigenix.domain.masterdata.supplier.SupplierError;
import de.effigenix.domain.masterdata.supplier.SupplierRepository;
import de.effigenix.shared.common.Result;
import de.effigenix.shared.persistence.UnitOfWork;
import de.effigenix.shared.security.ActorId;

public class CreateSupplier {

    private final SupplierRepository supplierRepository;
    private final UnitOfWork unitOfWork;

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

    public Result<SupplierError, Supplier> execute(CreateSupplierCommand cmd, ActorId performedBy) {
        // 1. Draft aus Command bauen (kein VO-Wissen im Use Case)
        var draft = new SupplierDraft(
                cmd.name(), cmd.phone(), cmd.email(), cmd.contactPerson(),
                cmd.street(), cmd.houseNumber(), cmd.postalCode(), cmd.city(), cmd.country(),
                cmd.paymentDueDays(), cmd.paymentDescription()
        );

        // 2. Aggregate erzeugen (validiert intern)
        Supplier supplier;
        switch (Supplier.create(draft)) {
            case Result.Failure(var err) -> { return Result.failure(err); }
            case Result.Success(var val) -> supplier = val;
        }

        // 3. Uniqueness-Check (Application-Concern: braucht Repository)
        switch (supplierRepository.existsByName(supplier.name())) {
            case Result.Failure(var err) ->
                { return Result.failure(new SupplierError.RepositoryFailure(err.message())); }
            case Result.Success(var exists) -> {
                if (exists) {
                    return Result.failure(new SupplierError.SupplierNameAlreadyExists(cmd.name()));
                }
            }
        }

        // 4. 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);
        });
    }
}
