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());

            int affectedRows = stmt.executeUpdate();
            if (affectedRows == 0)
            {
                throw new SQLException("unsuccessful");
            }

            try (ResultSet generatedKeys = stmt.getGeneratedKeys())
            {
                if (generatedKeys.next())
                {
                    return generatedKeys.getInt(1);
                } else
                {
                    throw new SQLException("unsuccessful");
                }
            }
        } catch (SQLException e)
        {
            e.printStackTrace();
        }

        return -1;
    }

    public List<Order> findByUserId(int userId) {

        String sql = "SELECT id, user_id, orderDate, total_price FROM orders WHERE user_id = ? ORDER BY orderDate DESC";
        List<Order> orders = new ArrayList<>();

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

            stmt.setInt(1, userId);
            try (ResultSet rs = stmt.executeQuery())
            {
                while (rs.next())
                {
                    Order order = new Order();
                    order.setId(rs.getInt("id"));
                    order.setUserId(rs.getInt("user_id"));
                    order.setCreatedAt(rs.getTimestamp("order_date").toLocalDateTime());
                    order.setTotalPrice(rs.getDouble("total_price"));
                    orders.add(order);
                }
            }

        } catch (SQLException e)
        {
            e.printStackTrace();
        }

        return orders;
    }

}