package dev.dao;

import dev.model.Order;

import java.util.List;
import dev.database.DatabaseConnection;
import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;

public class OrderDao {

    public int save(Order order) {

        // TODO:
        // Insert order and return generated id
        String sql = "INSERT INTO orders (user_id, total_amount) VALUES (?, ?)";
        try (Connection conn = DatabaseConnection.getConnection(); PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)){
            Field userIdField = Order.class.getDeclaredField("userId");
            Field totalPriceField = Order.class.getDeclaredField("totalPrice");
            userIdField.setAccessible(true);
            totalPriceField.setAccessible(true);
            stmt.setInt(1, (int) userIdField.get(order));
            stmt.setDouble(2, (double) totalPriceField.get(order));
            stmt.executeUpdate();

            try (ResultSet generatedKeys = stmt.getGeneratedKeys()){
                if (generatedKeys.next()){
                    return generatedKeys.getInt(1);
                }
            }
        }
        catch (SQLException | NoSuchFieldException | IllegalAccessException ex){
            ex.printStackTrace();
        }

        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 = ? ORDER BY order_date DESC";
        try (Connection conn = DatabaseConnection.getConnection(); PreparedStatement stmt = conn.prepareStatement(sql)){
            stmt.setInt(1, userId);
            try (ResultSet rs = stmt.executeQuery()){
                while (rs.next()){
                    Order order = new Order();
                    Field idField = Order.class.getDeclaredField("id");
                    Field userIdField = Order.class.getDeclaredField("userId");
                    Field createdAtField = Order.class.getDeclaredField("createdAt");
                    Field totalPriceField = Order.class.getDeclaredField("totalPrice");
                    idField.setAccessible(true);
                    userIdField.setAccessible(true);
                    createdAtField.setAccessible(true);
                    totalPriceField.setAccessible(true);
                    idField.set(order, rs.getInt("id"));
                    userIdField.set(order, rs.getInt("user_id"));
                    Timestamp timestamp = rs.getTimestamp("order_date");
                    if (timestamp != null){
                        createdAtField.set(order, timestamp.toLocalDateTime());
                    }

                    totalPriceField.set(order, rs.getDouble("total_amount"));
                    orders.add(order);
                }
            }
        }
        catch(SQLException | NoSuchFieldException | IllegalAccessException ex){
            ex.printStackTrace();
        }
        return orders;
    }

}