package dev.dao;

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

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
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, created_at, total_price) VALUES (?, ?, ?)";

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

            statement.setInt(1, order.getUserId());
            statement.setTimestamp(2, Timestamp.valueOf(order.getCreatedAt()));
            statement.setDouble(3, order.getTotalPrice());

            statement.executeUpdate();

            try (ResultSet generatedKeys = statement.getGeneratedKeys()) {

                if (generatedKeys.next()) {
                    return generatedKeys.getInt(1);
                }

                return -1;
            }

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

    public List<Order> findByUserId(int userId) {

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

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

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

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

            statement.setInt(1, userId);

            try (ResultSet resultSet = statement.executeQuery()) {

                while (resultSet.next()) {
                    orders.add(new Order(
                            resultSet.getInt("id"),
                            resultSet.getInt("user_id"),
                            resultSet.getTimestamp("created_at").toLocalDateTime(),
                            resultSet.getDouble("total_price")
                    ));
                }

                return orders;
            }

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

}