package ru.soune.nocopy.scheduler;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import ru.soune.nocopy.client.YooKassaClient;
import ru.soune.nocopy.entity.tarif.Tariff;
import ru.soune.nocopy.entity.tarif.TariffInfo;
import ru.soune.nocopy.entity.user.User;
import ru.soune.nocopy.repository.TariffInfoRepository;
import ru.soune.nocopy.repository.UserRepository;
import ru.soune.nocopy.service.mail.EmailService;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Component
@RequiredArgsConstructor
public class PaymentScheduler {

    private final TariffInfoRepository tariffInfoRepository;

    private final EmailService emailService;

    private final YooKassaClient yooKassaClient;

    private final UserRepository userRepository;

    @Scheduled(cron = "0 0 1 * * *")
    @Transactional
    public void processAutoRenewals() {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime renewalDate = now.plusDays(1);
        List<TariffInfo> forRenewal = tariffInfoRepository.findForAutoRenewal(renewalDate);

        for (TariffInfo tariffInfo : forRenewal) {
            try {
                if (tariffInfo.getPaymentMethodId() == null) {
                    tariffInfo.setAutoRenewal(false);
                    tariffInfoRepository.save(tariffInfo);
                    continue;
                }

                User user = userRepository.findByPersonalTariffInfo(tariffInfo);
                boolean success = yooKassaClient.createAutoPayment(
                        tariffInfo.getPaymentMethodId(),
                        tariffInfo.getTariff().getPrice(),
                        "Auto-renewal " + tariffInfo.getTariff().getName(),
                        String.valueOf(user.getId()));

                Tariff tariff = tariffInfo.getTariff();
                if (success) {
                    tariffInfo.setStartTariff(now);
                    tariffInfo.setEndTariff(now.plusMonths(1));

                    tariffInfoRepository.save(tariffInfo);

                    emailService.sendAutoRenewalSuccessEmail(user, tariff.getName(), tariff.getPrice(), renewalDate);
                } else {
                    emailService.sendAutoRenewalFailedEmail(user, tariff.getName(), tariff.getPrice());
                }
            } catch (Exception e) {
                log.error("Error processing auto-renewal for tariffInfo: " + tariffInfo.getId(), e);
            }
        }
    }
}
