package fr.eni.enchere.dal;

import fr.eni.enchere.bll.EnchereService;
import fr.eni.enchere.bll.UserService;
import fr.eni.enchere.bo.Enchere;
import fr.eni.enchere.bo.UserProfil;
import org.apache.catalina.User;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
@Repository
public class EnchereRepositoryImpl implements EnchereRepository {

    private final JdbcTemplate jdbcTemplate;
    private UserService userService;

    public EnchereRepositoryImpl(JdbcTemplate jdbcTemplate, UserService userService) {
        this.jdbcTemplate = jdbcTemplate;
        this.userService = userService;
    }

    public class EnchereRowMapper implements RowMapper<Enchere> {
        @Override
        public Enchere mapRow(ResultSet rs, int rowNum) throws SQLException {
            Enchere enchere = new Enchere();
            enchere.setId(rs.getInt("id"));
            enchere.setNoUtilisateur(rs.getInt("no_utilisateur"));
            enchere.setNoArticle(rs.getInt("no_article"));
            enchere.setMontantEnchere(rs.getInt("montant_enchere"));
            enchere.setDateEnchere(rs.getDate("date_enchere"));
            UserProfil user = userService.utilisateurById(rs.getInt("no_utilisateur"));
            enchere.setPseudoUtilisateur(user.getPseudo());
            return enchere;
        }
    }

    @Override
    public List<Enchere> findByIdUser(int idUser) {
        String sql = "SELECT * FROM ENCHERES WHERE no_utilisateur = ? AND isDelete = 0";
        List<Enchere> encheres = jdbcTemplate.query(sql, new EnchereRowMapper(), idUser);
        return encheres;
    }

    @Override
    public void delete(int id) {
        String sql = "UPDATE ENCHERES SET isDelete = 1 WHERE id = ?";
        jdbcTemplate.update(sql, id);
    }

    @Override
    public List<Enchere> findByIdArticle(int idArticle) {
        String sql = "SELECT * FROM ENCHERES WHERE no_article = ? AND isDelete = 0";
        List<Enchere> encheres = jdbcTemplate.query(sql, new EnchereRowMapper(), idArticle);
        return encheres;
    }

    @Override
    public void save(Enchere enchere) {
        String sql = "INSERT INTO ENCHERES (no_utilisateur, no_article, date_enchere, montant_enchere) VALUES (?, ?, ?, ?)";
        KeyHolder keyHolder = new GeneratedKeyHolder();
        jdbcTemplate.update(sql, enchere.getNoUtilisateur(), enchere.getNoArticle(), enchere.getDateEnchere(), enchere.getMontantEnchere());
        if (keyHolder.getKey() != null) {
            enchere.setId(keyHolder.getKey().intValue());
        }
    }
}
