package com.rjlresaka.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;

import javax.servlet.ServletContext;

import com.rjlresaka.util.DatabaseConnection;

public class PasswordResetDAO {

    public void createToken(int userId, String token, Timestamp expiresAt, ServletContext context) throws SQLException, ClassNotFoundException {
        String cleanup = "UPDATE password_reset_tokens SET used = 1 WHERE user_id = ? AND used = 0";
        String insert = "INSERT INTO password_reset_tokens (user_id, token, expires_at, used) VALUES (?, ?, ?, 0)";
        try (Connection connection = DatabaseConnection.getConnection(context);
             PreparedStatement cleanupStatement = connection.prepareStatement(cleanup);
             PreparedStatement insertStatement = connection.prepareStatement(insert)) {
            cleanupStatement.setInt(1, userId);
            cleanupStatement.executeUpdate();
            insertStatement.setInt(1, userId);
            insertStatement.setString(2, token);
            insertStatement.setTimestamp(3, expiresAt);
            insertStatement.executeUpdate();
        }
    }

    public Integer findValidUserIdByToken(String token, ServletContext context) throws SQLException, ClassNotFoundException {
        String sql = "SELECT user_id FROM password_reset_tokens WHERE token = ? AND used = 0 AND expires_at >= NOW() LIMIT 1";
        try (Connection connection = DatabaseConnection.getConnection(context);
             PreparedStatement statement = connection.prepareStatement(sql)) {
            statement.setString(1, token);
            try (ResultSet rs = statement.executeQuery()) {
                return rs.next() ? Integer.valueOf(rs.getInt("user_id")) : null;
            }
        }
    }

    public void markAsUsed(String token, ServletContext context) throws SQLException, ClassNotFoundException {
        String sql = "UPDATE password_reset_tokens SET used = 1 WHERE token = ?";
        try (Connection connection = DatabaseConnection.getConnection(context);
             PreparedStatement statement = connection.prepareStatement(sql)) {
            statement.setString(1, token);
            statement.executeUpdate();
        }
    }
}
