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;
import java.util.Objects;

public class OrderDao {

    public int save(Order order) {

        // TODO:
        // Insert order and return generated id

        try (Connection c = DatabaseConnection.getConnection()) {
            String insertQuery = "INSERT INTO orders (user_id, created_at, total_price) VALUES (?, ?, ?)";
            try (PreparedStatement pstmt = c.prepareStatement(insertQuery)) {
                pstmt.setInt(1, order.getUserId());
                pstmt.setTimestamp(2, Timestamp.valueOf(order.getCreatedAt()));
                pstmt.setDouble(3, order.getTotalPrice());
                pstmt.executeUpdate();
            }

            String selectQuery = "SELECT * FROM orders ORDER BY created_at DESC";
            try (Statement stmt = c.createStatement();
                 ResultSet rs = stmt.executeQuery(selectQuery)) {

                while (rs.next()) {
                    int user_id = rs.getInt("user_id");
                    if (user_id == order.getUserId()) {
                        return rs.getInt("id");
                    }
                }
            }
        }
        catch (SQLException e) {
            System.err.println("Error in connection with database: " + e.getMessage());
            e.printStackTrace();
        }

        return -1;
    }

    public List<Order> findByUserId(int userId) {

        // TODO:
        // Retrieve all orders of a user

        List<Order> orders = new ArrayList<>();
        try (Connection c = DatabaseConnection.getConnection()) {
            String selectQuery = "SELECT * FROM orders";
            try (Statement stmt = c.createStatement();
                 ResultSet rs = stmt.executeQuery(selectQuery)) {

                while (rs.next()) {
                    int user_id = rs.getInt("user_id");
                    if (user_id == userId) {
                        int id = rs.getInt("id");
                        LocalDateTime LDT = rs.getTimestamp("created_at").toLocalDateTime();
                        double total_price = rs.getDouble("total_price");
                        Order order = new Order(id, user_id, LDT, total_price);
                        orders.add(order);
                    }
                }
            }
        }
        catch (SQLException e) {
            System.err.println("Error in connection with database: " + e.getMessage());
            e.printStackTrace();
        }

        return orders;
    }

}