package pl.polskalokalnie.mailconfig;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Dostep do jednorekordowej konfiguracji SMTP i bramki SMS. Sekrety (haslo, klucz API) sa
 * nadpisywane tylko przy jawnej zmianie; puste pole w zadaniu zachowuje dotychczasowa wartosc.
 * Metody get* zwracaja encje z sekretami wylacznie na uzytek wewnetrzny (sendery) - nie sa
 * serializowane do klienta.
 */
@Service
public class MailConfigService {

    private static final long SINGLETON_ID = 1L;

    private final SmtpConfigRepository smtpConfigRepository;
    private final SmsGatewayConfigRepository smsGatewayConfigRepository;

    public MailConfigService(SmtpConfigRepository smtpConfigRepository,
            SmsGatewayConfigRepository smsGatewayConfigRepository) {
        this.smtpConfigRepository = smtpConfigRepository;
        this.smsGatewayConfigRepository = smsGatewayConfigRepository;
    }

    @Transactional
    public SmtpConfig getSmtp() {
        return smtpConfigRepository.findById(SINGLETON_ID).orElseGet(() -> {
            SmtpConfig config = new SmtpConfig();
            config.setId(SINGLETON_ID);
            return smtpConfigRepository.save(config);
        });
    }

    @Transactional
    public SmsGatewayConfig getSms() {
        return smsGatewayConfigRepository.findById(SINGLETON_ID).orElseGet(() -> {
            SmsGatewayConfig config = new SmsGatewayConfig();
            config.setId(SINGLETON_ID);
            return smsGatewayConfigRepository.save(config);
        });
    }

    @Transactional
    public SmtpConfig updateSmtp(SmtpConfigRequest request) {
        SmtpConfig config = getSmtp();
        config.setHost(trimToNull(request.host()));
        config.setPort(request.port());
        if (request.sslEnabled() != null) {
            config.setSslEnabled(request.sslEnabled());
        }
        config.setUsername(trimToNull(request.username()));
        config.setFromName(trimToNull(request.fromName()));
        config.setContactFormRecipient(trimToNull(request.contactFormRecipient()));
        if (request.enabled() != null) {
            config.setEnabled(request.enabled());
        }
        // Haslo zmieniamy tylko gdy podane (niepuste) - inaczej zachowujemy dotychczasowe.
        String password = request.password();
        if (password != null && !password.isBlank()) {
            config.setPassword(password);
        }
        return smtpConfigRepository.save(config);
    }

    @Transactional
    public SmsGatewayConfig updateSms(SmsConfigRequest request) {
        SmsGatewayConfig config = getSms();
        config.setEndpointUrl(trimToNull(request.endpointUrl()));
        config.setCreator(trimToNull(request.creator()));
        if (request.timeoutSeconds() != null) {
            config.setTimeoutSeconds(request.timeoutSeconds());
        }
        if (request.enabled() != null) {
            config.setEnabled(request.enabled());
        }
        String apiKey = request.apiKey();
        if (apiKey != null && !apiKey.isBlank()) {
            config.setApiKey(apiKey);
        }
        return smsGatewayConfigRepository.save(config);
    }

    private static String trimToNull(String value) {
        if (value == null) {
            return null;
        }
        String trimmed = value.trim();
        return trimmed.isEmpty() ? null : trimmed;
    }
}
