package com.rjlresaka.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContext;

import com.rjlresaka.model.User;
import com.rjlresaka.util.DatabaseConnection;

public class UserDAO {

    public boolean emailExists(String email, ServletContext context) throws SQLException, ClassNotFoundException {
        String sql = "SELECT id FROM users WHERE email = ?";
        try (Connection connection = DatabaseConnection.getConnection(context);
             PreparedStatement statement = connection.prepareStatement(sql)) {
            statement.setString(1, email);
            try (ResultSet rs = statement.executeQuery()) {
                return rs.next();
            }
        }
    }

    public boolean usernameExists(String username, ServletContext context) throws SQLException, ClassNotFoundException {
        String sql = "SELECT id FROM users WHERE username = ?";
        try (Connection connection = DatabaseConnection.getConnection(context);
             PreparedStatement statement = connection.prepareStatement(sql)) {
            statement.setString(1, username);
            try (ResultSet rs = statement.executeQuery()) {
                return rs.next();
            }
        }
    }

    public User create(User user, ServletContext context) throws SQLException, ClassNotFoundException {
        String sql = "INSERT INTO users (full_name, username, email, password_hash, avatar_color, bio) VALUES (?, ?, ?, ?, ?, ?)";
        try (Connection connection = DatabaseConnection.getConnection(context);
             PreparedStatement statement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
            statement.setString(1, user.getFullName());
            statement.setString(2, user.getUsername());
            statement.setString(3, user.getEmail());
            statement.setString(4, user.getPasswordHash());
            statement.setString(5, user.getAvatarColor());
            statement.setString(6, user.getBio());
            statement.executeUpdate();
            try (ResultSet keys = statement.getGeneratedKeys()) {
                if (keys.next()) {
                    user.setId(keys.getInt(1));
                }
            }
            return user;
        }
    }

    public User findById(int id, ServletContext context) throws SQLException, ClassNotFoundException {
        String sql = "SELECT * FROM users WHERE id = ? LIMIT 1";
        try (Connection connection = DatabaseConnection.getConnection(context);
             PreparedStatement statement = connection.prepareStatement(sql)) {
            statement.setInt(1, id);
            try (ResultSet rs = statement.executeQuery()) {
                return rs.next() ? mapUser(rs) : null;
            }
        }
    }

    public User findByEmail(String email, ServletContext context) throws SQLException, ClassNotFoundException {
        String sql = "SELECT * FROM users WHERE email = ? LIMIT 1";
        try (Connection connection = DatabaseConnection.getConnection(context);
             PreparedStatement statement = connection.prepareStatement(sql)) {
            statement.setString(1, email);
            try (ResultSet rs = statement.executeQuery()) {
                return rs.next() ? mapUser(rs) : null;
            }
        }
    }

    public User findByEmailOrUsername(String value, ServletContext context) throws SQLException, ClassNotFoundException {
        String sql = "SELECT * FROM users WHERE email = ? OR username = ? LIMIT 1";
        try (Connection connection = DatabaseConnection.getConnection(context);
             PreparedStatement statement = connection.prepareStatement(sql)) {
            statement.setString(1, value);
            statement.setString(2, value);
            try (ResultSet rs = statement.executeQuery()) {
                return rs.next() ? mapUser(rs) : null;
            }
        }
    }

    public List<User> findOtherUsers(int currentUserId, ServletContext context) throws SQLException, ClassNotFoundException {
        String sql = "SELECT * FROM users WHERE id <> ? ORDER BY full_name ASC";
        List<User> users = new ArrayList<User>();
        try (Connection connection = DatabaseConnection.getConnection(context);
             PreparedStatement statement = connection.prepareStatement(sql)) {
            statement.setInt(1, currentUserId);
            try (ResultSet rs = statement.executeQuery()) {
                while (rs.next()) {
                    users.add(mapUser(rs));
                }
            }
        }
        return users;
    }

    public void updatePassword(int userId, String passwordHash, ServletContext context) throws SQLException, ClassNotFoundException {
        String sql = "UPDATE users SET password_hash = ? WHERE id = ?";
        try (Connection connection = DatabaseConnection.getConnection(context);
             PreparedStatement statement = connection.prepareStatement(sql)) {
            statement.setString(1, passwordHash);
            statement.setInt(2, userId);
            statement.executeUpdate();
        }
    }

    private User mapUser(ResultSet rs) throws SQLException {
        User user = new User();
        user.setId(rs.getInt("id"));
        user.setFullName(rs.getString("full_name"));
        user.setUsername(rs.getString("username"));
        user.setEmail(rs.getString("email"));
        user.setPasswordHash(rs.getString("password_hash"));
        user.setAvatarColor(rs.getString("avatar_color"));
        user.setBio(rs.getString("bio"));
        user.setCreatedAt(rs.getTimestamp("created_at"));
        user.setUpdatedAt(rs.getTimestamp("updated_at"));
        return user;
    }
}
