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.shared.common.Result;
import org.springframework.context.annotation.Profile;
import org.springframework.jdbc.core.simple.JdbcClient;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;

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

    private final JdbcClient jdbc;

    public JdbcBatchNumberGenerator(JdbcClient jdbc) {
        this.jdbc = jdbc;
    }

    @Override
    @Transactional
    public Result<BatchError, BatchNumber> generateNext(LocalDate date) {
        try {
            var existing = jdbc.sql(
                            "SELECT last_sequence FROM batch_number_sequences WHERE production_date = :date FOR UPDATE")
                    .param("date", date)
                    .query(Integer.class)
                    .optional();

            int nextSequence;
            if (existing.isPresent()) {
                nextSequence = existing.get() + 1;
                jdbc.sql("UPDATE batch_number_sequences SET last_sequence = :seq WHERE production_date = :date")
                        .param("seq", nextSequence)
                        .param("date", date)
                        .update();
            } else {
                nextSequence = 1;
                jdbc.sql("INSERT INTO batch_number_sequences (production_date, last_sequence) VALUES (:date, :seq)")
                        .param("date", date)
                        .param("seq", 1)
                        .update();
            }

            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()));
        }
    }
}
