package dev.dao;

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

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

public class OrderDao {

    public int save(Order order) {

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

        try (
                Connection connection = DatabaseConnection.getConnection();
                PreparedStatement statement = connection.prepareStatement(sql)
        ) {

            statement.setInt(1, order.getUserId());
            statement.setDouble(2, order.getTotalPrice());

            ResultSet resultSet = statement.executeQuery();

            if (resultSet.next()) {
                return resultSet.getInt("id");
            }

        } catch (SQLException e) {
            System.out.println("Error saving order: " + e.getMessage());
        }

        return -1;
    }

    public List<Order> findByUserId(int userId) {

        String sql = "SELECT id, user_id, created_at, total_price FROM orders WHERE user_id = ?";

        List<Order> orders = new ArrayList<>();

        try (
                Connection connection = DatabaseConnection.getConnection();
                PreparedStatement statement = connection.prepareStatement(sql)
        ) {

            statement.setInt(1, userId);

            ResultSet resultSet = statement.executeQuery();

            while (resultSet.next()) {

                Order order = new Order();

                order.setId(resultSet.getInt("id"));
                order.setUserId(resultSet.getInt("user_id"));
                order.setCreatedAt(resultSet.getTimestamp("created_at").toLocalDateTime());
                order.setTotalPrice(resultSet.getDouble("total_price"));

                orders.add(order);
            }

        } catch (SQLException e) {
            System.out.println("Error loading orders: " + e.getMessage());
        }

        return orders;
    }
}