package com.hpay.hpay_mobile_api.services;

import org.springframework.beans.factory.annotation.Autowired;
import com.hpay.hpay_mobile_api.repositories.CompteRepository;
import com.hpay.hpay_mobile_api.entities.Compte;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

@Service
public class CompteService {

    @Autowired
    private CompteRepository compteRepository;

    public List<Compte> getAllComptes() {
        return compteRepository.findAll();
    }

    public Optional<Compte> getCompteById(Long id) {
        return compteRepository.findById(id);
    }

    public Compte createCompte(Compte compte) {
        return compteRepository.save(compte);
    }

    public void deleteCompte(Long id) {
        compteRepository.deleteById(id);
    }


    /**
     * Génère un numéro de compte unique selon le format yyMMddHHmmss.
     * Vérifie qu'il n'existe pas déjà en base. Réessaie si nécessaire.
     */
    public String generateUniqueNumCompte() {
        String numCompte;
        boolean exists;

        do {
            numCompte = generateTimeBasedNum();

            exists = compteRepository.existsByNumCompte(numCompte);

            if (exists) {
                try {
                    TimeUnit.MILLISECONDS.sleep(5);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    throw new RuntimeException("Thread interrupted while generating numCompte", e);
                }
            }

        } while (exists);

        try {
            TimeUnit.MILLISECONDS.sleep(1005);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new RuntimeException("Thread interrupted while generating numCompte", e);
        }

        return numCompte;
    }


    /**
     * Génère un numéro de compte basé sur la date/heure actuelle au format yyMMddHHmmss
     */
    private String generateTimeBasedNum() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyMMddHHmmss");
        return formatter.format(new Date());
    }


    public Optional<Compte> findById(Long id) {
        return compteRepository.findById(id);
    }

}
