package dev.dao;

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

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

public class OrderDao {

    public int save(Order order) {
        String sql = "INSERT INTO orders(user_id,created_at,total_price) VALUES(?,?,?)";

        try {
            PreparedStatement stmt = DatabaseConnection.getConnection().prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            stmt.setInt(1, order.getUserId());
            stmt.setTimestamp(2, Timestamp.valueOf(order.getCreatedAt()));
            stmt.setDouble(3, order.getTotalPrice());
            stmt.executeUpdate();

            ResultSet keys = stmt.getGeneratedKeys();
            if (keys.next()){
                int orderId = keys.getInt(1);
                order.setId(orderId);
                return orderId;
            }
        } catch (SQLException e) {
            System.err.println("Unable to add order: " + e.getMessage());
        }

        return -1;
    }

    public List<Order> findByUserId(int userId) {

        List<Order> result = new ArrayList<>();
        String sql = "SELECT * FROM orders WHERE user_id=?";

        try {
            PreparedStatement stmt = DatabaseConnection.getConnection().prepareStatement(sql);
            stmt.setInt(1,userId);

            ResultSet rs = stmt.executeQuery();

            while (rs.next()){
                result.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("Unable to find user: " + e.getMessage());
        }

        return result;
    }
}
