package de.effigenix.infrastructure.production.persistence;

import de.effigenix.domain.production.BatchError;
import de.effigenix.domain.production.BatchNumber;
import de.effigenix.domain.production.BatchNumberGenerator;
import de.effigenix.infrastructure.production.persistence.entity.BatchNumberSequenceEntity;
import de.effigenix.infrastructure.production.persistence.repository.BatchNumberSequenceJpaRepository;
import de.effigenix.shared.common.Result;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;

@Component
@Profile("!no-db")
public class JpaBatchNumberGenerator implements BatchNumberGenerator {

    private final BatchNumberSequenceJpaRepository sequenceRepository;

    public JpaBatchNumberGenerator(BatchNumberSequenceJpaRepository sequenceRepository) {
        this.sequenceRepository = sequenceRepository;
    }

    @Override
    @Transactional
    public Result<BatchError, BatchNumber> generateNext(LocalDate date) {
        try {
            var sequence = sequenceRepository.findByProductionDate(date);
            int nextSequence;
            if (sequence.isPresent()) {
                nextSequence = sequence.get().getLastSequence() + 1;
                sequence.get().setLastSequence(nextSequence);
            } else {
                nextSequence = 1;
                sequenceRepository.save(new BatchNumberSequenceEntity(date, 1));
            }
            if (nextSequence > 999) {
                return Result.failure(new BatchError.ValidationFailure(
                        "Maximum batch number sequence (999) reached for date " + date));
            }
            return Result.success(BatchNumber.generate(date, nextSequence));
        } catch (Exception e) {
            return Result.failure(new BatchError.RepositoryFailure(e.getMessage()));
        }
    }
}
