package dev.dao;

import dev.database.DatabaseConnection;
import dev.model.Order;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

public class OrderDao {

    public int save(Order order) {

        String sql = "INSERT INTO orders(user_id, created_at, total_price) VALUES(?, ?, ?)";

        try{

            PreparedStatement st = DatabaseConnection.getConnection().prepareStatement(sql);
            st.setInt(1, order.getUserId());
            st.setTimestamp(2, Timestamp.valueOf(order.getCreatedAt()));
            st.setDouble(3, order.getTotalPrice());

            st.executeUpdate();
            ResultSet rsKeys = st.getGeneratedKeys();
            if(rsKeys.next()){
                int orderId = rsKeys.getInt(1);
                order.setId(orderId);
                return orderId;
            }

            st.close();

        } catch (SQLException e) {
            System.err.println("Failed to add order " + e.getMessage());
        }

        return -1;
    }

    public List<Order> findByUserId(int userId) {

        String sql = "SELECT * FROM orders WHERE user_id=?";
        List<Order> result = new ArrayList<>();

        try {

            PreparedStatement st = DatabaseConnection.getConnection().prepareStatement(sql);
            st.setInt(1,userId);

            ResultSet rs = st.executeQuery();
            while (rs.next()){
                result.add(new Order(
                        rs.getInt("id"),
                        rs.getInt("user_id"),
                        rs.getTimestamp("created_at").toLocalDateTime(),
                        rs.getInt("total_price")
                ));
            }

            st.close();

        } catch (SQLException e) {
            System.err.println("Unable to find user: " + e.getMessage());
        }

        return result;

    }

}