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 (?, ?)";
        try (Connection conn = DatabaseConnection.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
            stmt.setInt(1, order.getUserId());
            stmt.setDouble(2, order.getTotalPrice());
            stmt.executeUpdate();

            try (ResultSet generatedKeys = stmt.getGeneratedKeys()) {
                if (generatedKeys.next()) {
                    return generatedKeys.getInt(1);
                }
            }
        } catch (SQLException e) {
            System.err.println("Database error while saving order: " + e.getMessage());
        }
        return -1;
    }

    public List<Order> findByUserId(int userId) {
        List<Order> orders = new ArrayList<>();
        String sql = "SELECT * FROM orders WHERE user_id = ? ORDER BY created_at DESC";
        try (Connection conn = DatabaseConnection.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {
            stmt.setInt(1, userId);
            try (ResultSet rs = stmt.executeQuery()) {
                while (rs.next()) {
                    orders.add(new Order(
                            rs.getInt("id"),
                            rs.getInt("user_id"),
                            rs.getTimestamp("created_at").toLocalDateTime(),
                            rs.getDouble("total_price")
                    ));
                }
            }
        } catch (SQLException e) {
            System.err.println("Database error while searching history: " + e.getMessage());
        }
        return orders;
    }
}