package fr.eni.enchere.dal;

import fr.eni.enchere.bo.Bank;
import fr.eni.enchere.bo.ForgotPassword;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Calendar;

@Repository
public class BankRepositoryImpl implements BankRepository {

    @Autowired
    private final JdbcTemplate jdbcTemplate;
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    public BankRepositoryImpl(JdbcTemplate jdbcTemplate, NamedParameterJdbcTemplate namedParameterJdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
        this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
    }

    public class BankRowMapper implements RowMapper<Bank> {
        @Override
        public Bank mapRow(ResultSet rs, int rowNum) throws SQLException {
            Bank bank = new Bank();
            bank.setId(rs.getInt("id"));
            bank.setCartNumber(rs.getString("cardNumber"));
            bank.setCartExpired(rs.getString("cardExpired"));
            bank.setCartCVV(rs.getInt("cardCVV"));
            bank.setCartName(rs.getString("cardName"));
            bank.setCartAmount(rs.getFloat("credit"));
            return bank;
        }
    }

    @Override
    public Bank verifCart(String cartNumber, String cartExpired, int cartCVV) {
        String sql = "SELECT * FROM CREDITCARD WHERE cardNumber = ? AND cardExpired = ? AND cardCVV = ?";
        try {
            return jdbcTemplate.queryForObject(sql, new BankRepositoryImpl.BankRowMapper(), cartNumber, cartExpired, cartCVV);
        } catch (EmptyResultDataAccessException e) {
            // Aucun résultat trouvé, retourne null
            return null;
        }
    }

    @Override
    public void editAmmountCart(Bank bank, float ammount) {
        String sql = "UPDATE CREDITCARD SET credit = ? WHERE cardNumber = ? AND cardExpired = ? AND cardCVV = ?";
        jdbcTemplate.update(sql, ammount, bank.getCartNumber(), bank.getCartExpired(), bank.getCartCVV());
    }


}
