package dev.dao;

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

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDao {

    public boolean save(User user) {

        String sql = "INSERT INTO users (username, password_hash, email) VALUES (?, ?, ?)";

        try{

            PreparedStatement st = DatabaseConnection.getConnection().prepareStatement(sql);
            st.setString(1, user.getUsername());
            st.setString(2, user.getPassword());
            st.setString(3, user.getEmail());
            st.executeUpdate();
            st.close();

            return true;

        } catch (SQLException e) {
            System.err.println("Failed to save user " + e.getMessage());
        }

        return false;
    }

    public User findByUsername(String username) {

        String sql = "SELECT * FROM users WHERE username=?";
        User result = null;

        try{

            PreparedStatement st = DatabaseConnection.getConnection().prepareStatement(sql);
            st.setString(1, username);

            ResultSet rs = st.executeQuery();
            if(rs.next()){
                result = new User(
                        rs.getInt("id"),
                        rs.getString("username"),
                        rs.getString("password_hash"),
                        rs.getString("email")
                );
            }
            st.close();

        } catch (SQLException e) {
            System.err.println("Failed to fild user " + e.getMessage());
        }

        return result;

    }

}