package com.nisum.servlet;

import com.nisum.dao.AddressDAO;
import com.nisum.model.UserAddress;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

public class AddressServlet extends HttpServlet {

    private final AddressDAO addressDAO = new AddressDAO();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {

        String userIdParam = req.getParameter("userId");
        String cartId = req.getParameter("cartId");

        if (userIdParam == null || userIdParam.trim().isEmpty()) {
            res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing userId");
            return;
        }

        try {
            int userId = Integer.parseInt(userIdParam.trim());

            // Fetch addresses from DB using DAO
            List<UserAddress> addresses = addressDAO.getUserAddresses(userId);

            // Set request attributes for JSP
            req.setAttribute("userId", userId);
            req.setAttribute("cartId", cartId); // may be null
            req.setAttribute("addresses", addresses);

            // Forward to JSP
            req.getRequestDispatcher("/jsp/addresses.jsp").forward(req, res);

        } catch (NumberFormatException e) {
            res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid userId");
        } catch (SQLException e) {
            throw new ServletException("Database error while fetching addresses", e);
        }
    }
}
