package dev.dao;

import dev.database.DatabaseConnection;
import dev.model.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.mindrot.jbcrypt.BCrypt;

public class UserDao {

    public boolean save(User user) {

        String hashedPassword = BCrypt.hashpw(user.getPassword(), BCrypt.gensalt());
        String query ="INSERT INTO users (username, password_hash, email) VALUES (?, ?, ?)";

        try(Connection c = DatabaseConnection.getConnection();
            PreparedStatement pst = c.prepareStatement(query)) {

            pst.setString(1 , user.getUsername());
            pst.setString(2 , hashedPassword);
            pst.setString(3 , user.getEmail());


            int result = pst.executeUpdate();
            if(result==1){
                return true;
            }


        } catch (SQLException e) {
            System.out.println(e.getMessage());
        };

        return false;
    }

    public User findByUsername(String userName) {

        String query = "SELECT * FROM users WHERE username = ?";

        try (Connection c = DatabaseConnection.getConnection();
             PreparedStatement pst = c.prepareStatement(query)) {

            pst.setString(1, userName);

            try (ResultSet rst = pst.executeQuery()) {
                if (rst.next()) {
                    User user = new User(rst.getInt("id"),
                            rst.getString("username"),
                            rst.getString("password_hash"),
                            rst.getString("email"));
                    return user;
                }

            }


        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }

        return null;

    }

}