package dev.dao;

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

import java.sql.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

public class OrderDao {

    public int save(Order order) {

        // TODO:
        // Insert order and return generated id
        String sql = "INSERT INTO orders (user_id, total_price) VALUES (?, ?)";
        try (Connection conn = DatabaseConnection.getConnection();) {
            PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            stmt.setInt(1, order.getUserId());
            stmt.setDouble(2, order.getTotalPrice());
            int row = stmt.executeUpdate();
            if (row > 0) {
                try (ResultSet generatedKeys = stmt.getGeneratedKeys()) {
                    if (generatedKeys.next()) {
                        return generatedKeys.getInt(1);
                    }
                }
            }
        } catch (SQLException ex) {
            throw new RuntimeException(ex);
        }

        return -1;
    }

    public List<Order> findByUserId(int userId) {

        // TODO:
        // Retrieve all orders of a user
        List<Order> orders = new ArrayList<>();
        String sql = "SELECT * FROM orders WHERE user_id = ?";
        try(Connection conn = DatabaseConnection.getConnection();
            PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setInt(1, userId);
            try (ResultSet rs = stmt.executeQuery()){
                while (rs.next())
                {
                    int id = rs.getInt("id");
                    int orderUserId = rs.getInt("user_id");
                    LocalDateTime localDateTime = rs.getTimestamp("created_at").toLocalDateTime();
                    double totalPrice = rs.getDouble("total_price");
                    Order order = new Order(id, orderUserId, localDateTime, totalPrice);
                    orders.add(order);
                }
            }
            return orders;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

}