package dev.dao;

import dev.database.DatabaseConnection;
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) {

        // Insert order and return generated id
        String sql = "INSERT INTO orders (user_id, total_price, created_at) VALUES(?, ?, ?) RETURNING id";

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

            preparedStatement.setInt(1, order.getUserId());
            preparedStatement.setDouble(2, order.getTotalPrice());
            preparedStatement.setTimestamp(3, Timestamp.valueOf(LocalDateTime.now()));

            ResultSet resultSet = preparedStatement.executeQuery();

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

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        return -1;
    }

    public List<Order> findByUserId(int userId) {

        // Retrieve all orders of a user
        String sql = "SELECT * FROM orders WHERE user_id=?";
        List<Order> orders = new ArrayList<>();

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

            preparedStatement.setInt(1, userId);

            ResultSet resultSet = preparedStatement.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) {
            throw new RuntimeException(e);
        }
        return orders;
    }

}