package dev.dao;

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

import java.sql.*;
import java.util.Objects;

public class UserDao {

    public boolean save(User user) {

        // TODO:
        // Insert user into database

        try (Connection c = DatabaseConnection.getConnection()) {
            String insertQuery = "INSERT INTO users (username, password_hash, email) VALUES (?, ?, ?)";
            try (PreparedStatement pstmt = c.prepareStatement(insertQuery)) {
                pstmt.setString(1, user.getUsername());
                pstmt.setString(2, user.getPassword());
                pstmt.setString(3, user.getEmail());
                pstmt.executeUpdate();
                return true;
            }
        }
        catch (SQLException e) {
            System.err.println("Error in connection with database: " + e.getMessage());
            e.printStackTrace();
        }

        return false;
    }

    public User findByUsername(String username) {

        // TODO:
        // Find a user by username

        try (Connection c = DatabaseConnection.getConnection()) {
            String selectQuery = "SELECT * FROM users";
            try (Statement stmt = c.createStatement();
                 ResultSet rs = stmt.executeQuery(selectQuery)) {

                while (rs.next()) {
                    String Username = rs.getString("username");
                    if (Objects.equals(Username, username)) {
                        int id = rs.getInt("id");
                        String password = rs.getString("password_hash");
                        String email = rs.getString("email");
                        return new User(id, username, password, email);
                    }
                }
            }
        }
        catch (SQLException e) {
            System.err.println("Error in connection with database: " + e.getMessage());
            e.printStackTrace();
        }

        return null;
    }

}