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;

public class UserDao {

    /**
     * Inserts a new user. The password passed in here is expected to already
     * be hashed by the service layer. Returns true if the insert worked.
     */
    public boolean save(User user) {

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

        // try-with-resources closes the connection and statement automatically.
        try (Connection conn = DatabaseConnection.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, user.getUsername());
            stmt.setString(2, user.getPassword());
            stmt.setString(3, user.getEmail());

            int rows = stmt.executeUpdate();
            return rows > 0;

        } catch (SQLException e) {
            System.out.println("Error while saving user: " + e.getMessage());
            return false;
        }
    }

    /**
     * Looks up a user by username. Returns null if nobody matches.
     */
    public User findByUsername(String username) {

        String sql = "SELECT id, username, password, email FROM users WHERE username = ?";

        try (Connection conn = DatabaseConnection.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, username);

            try (ResultSet rs = stmt.executeQuery()) {
                if (rs.next()) {
                    return new User(
                            rs.getInt("id"),
                            rs.getString("username"),
                            rs.getString("password"),
                            rs.getString("email")
                    );
                }
            }

        } catch (SQLException e) {
            System.out.println("Error while finding user: " + e.getMessage());
        }

        return null;
    }

}
