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 ps = DatabaseConnection.getConnection().prepareStatement(sql);
            ps.setString(1, user.getUsername());
            ps.setString(2, user.getPasswordHash());
            ps.setString(3, user.getEmail());
            ps.executeUpdate();
            return true;
        } catch (SQLException e) {

            System.out.println("fail to save user: " + e.getMessage());
        }

        return false;
    }

    public User findByUsername(String username) {

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

        User result = null;


        try {
            PreparedStatement stmt = DatabaseConnection.getConnection().prepareStatement(sql);
            stmt.setString(1, username);

            ResultSet rs = stmt.executeQuery();

            if (rs.next()){
                result = new User(
                        rs.getInt("id"),
                        rs.getString("username"),
                        rs.getString("password_hash"),
                        rs.getString("email")
                );
            }
        } catch (SQLException e) {
            System.err.println("Unable to find user: " + e.getMessage());
        }
        return result;
    }

}