package dev.dao;

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

import java.math.BigDecimal;
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, total_price) VALUES (?, ?)";

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

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

            stmt.executeUpdate();

            try (ResultSet rs = stmt.getGeneratedKeys()) {
                if (rs.next()) {
                    return rs.getInt(1);
                }
            }

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

        return -1;
    }

    public List<Order> findByUserId(int userId) {

        // TODO:
        // Retrieve all orders of a user
        List<Order> orders = new ArrayList<>();
        String sql = "SELECT id, user_id, created_at, total_price FROM orders WHERE user_id = ?";

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

            stmt.setInt(1, userId);

            try (ResultSet rs = stmt.executeQuery()) {
                while (rs.next()) {
                    int id = rs.getInt("id");
                    int uId = rs.getInt("user_id");
                    Timestamp createdAt = rs.getTimestamp("created_at");
                    BigDecimal totalPrice = rs.getBigDecimal("total_price");

                    orders.add(new Order(id, uId, createdAt.toLocalDateTime(), totalPrice));
                }
            }

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

        return orders;
    }

}