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 query = "INSERT INTO orders (user_id, total_price) VALUES (?, ?)";

        try (Connection conn = DatabaseConnection.getConnection();
             PreparedStatement stmt = conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS)) {

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

            int affectedRows = stmt.executeUpdate();
            if (affectedRows > 0) {
                try (ResultSet generatedKeys = stmt.getGeneratedKeys()) {
                    if (generatedKeys.next()) {
                        return generatedKeys.getInt(1); // برگرداندن آیدی خودکار تولید شده فاکتور
                    }
                }
            }
        } catch (SQLException e) {
            System.err.println("Error saving order: " + e.getMessage());
        }
        return -1;
    }

    public List<Order> findByUserId(int userId) {
        List<Order> orders = new ArrayList<>();
        String query = "SELECT * FROM orders WHERE user_id = ? ORDER BY created_at DESC";

        try (Connection conn = DatabaseConnection.getConnection();
             PreparedStatement stmt = conn.prepareStatement(query)) {

            stmt.setInt(1, userId);

            try (ResultSet rs = stmt.executeQuery()) {
                while (rs.next()) {
                    Order order = new Order(
                            rs.getInt("id"),
                            rs.getInt("user_id"),
                            rs.getTimestamp("created_at").toLocalDateTime(),
                            rs.getDouble("total_price")
                    );
                    orders.add(order);
                }
            }
        } catch (SQLException e) {
            System.err.println("Error retrieving user orders: " + e.getMessage());
        }
        return orders;
    }
}