package dev.dao;

import dev.model.User;

import java.sql.*;

public class UserDao
{
    private final Connection connection;

    public UserDao(Connection connection) {this.connection = connection;}

    public boolean save(User user)
    {
        String sql = """
            INSERT INTO users (username, password, email)
            VALUES (?, ?, ?)
        """;

        try (PreparedStatement ps = connection.prepareStatement(sql))
        {
            ps.setString(1, user.getUsername());
            ps.setString(2, user.getPassword());
            ps.setString(3, user.getEmail());

            int rowsAffected = ps.executeUpdate();

            return rowsAffected > 0;

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

    public User findByUsername(String username)
    {
        String sql = """
            SELECT id, username, password, email
            FROM users
            WHERE username = ?
        """;

        try (PreparedStatement ps = connection.prepareStatement(sql))
        {
            ps.setString(1, username);

            try (ResultSet rs = ps.executeQuery())
            {
                if (rs.next())
                {
                    User user = new User();

                    user.setId(rs.getInt("id"));
                    user.setUsername(rs.getString("username"));
                    user.setPassword(rs.getString("password"));
                    user.setEmail(rs.getString("email"));

                    return user;
                }
            }

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

        return null;
    }
}