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, order_date, total_price) VALUES (?, ?, ?)";

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

            ps.setInt(1, order.getUserId());
            ps.setTimestamp(2, order.getCreatedAt());
            ps.setDouble(3, order.getTotalPrice());

            int rowsAffected = ps.executeUpdate();

            if (rowsAffected == 1) {
                ResultSet rs = ps.getGeneratedKeys();
                if (rs.next()) {
                    return rs.getInt(1);
                }
            }

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

        return -1;
    }

    public List<Order> findByUserId(int userId) {
        String query = "SELECT uid, user_id, order_date, total_price FROM orders WHERE user_id = ?";
        List<Order> orders = new ArrayList<>();

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

            ps.setInt(1, userId);
            ResultSet rs = ps.executeQuery();

            while (rs.next()) {
                Order order = new Order();
                order.setId(rs.getInt("uid"));
                order.setUserId(rs.getInt("user_id"));
                order.setCreatedAt(rs.getTimestamp("order_date"));
                order.setTotalPrice(rs.getDouble("total_price"));
                orders.add(order);
            }

            return orders;

        } catch (SQLException e) {
            System.err.println("Error finding orders: " + e.getMessage());
            return new ArrayList<>();
        }
    }

    public Order findById(int orderId) {
        String query = "SELECT uid, user_id, order_date, total_price FROM orders WHERE uid = ?";

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

            ps.setInt(1, orderId);
            ResultSet rs = ps.executeQuery();

            if (rs.next()) {
                Order order = new Order();
                order.setId(rs.getInt("uid"));
                order.setUserId(rs.getInt("user_id"));
                order.setCreatedAt(rs.getTimestamp("order_date"));
                order.setTotalPrice(rs.getDouble("total_price"));
                return order;
            }

        } catch (SQLException e) {
            System.err.println("Error finding order by ID: " + e.getMessage());
        }

        return null;
    }
}