package dev.dao;

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

import java.sql.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

public class OrderDao {

    public int save(Order order) {

        LocalDateTime now = LocalDateTime.now();
        String query = "INSERT INTO customer_orders (user_id, time, total_price) VALUES (?, ?, ?)";

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

            pst.setInt(1 , order.getUserId());
            pst.setTimestamp(2 , Timestamp.valueOf(now));
            pst.setDouble(3 , order.getTotalPrice());

            int i = pst.executeUpdate();
            if(i==1) System.out.println("Order saved");

            try (ResultSet generatedKeys = pst.getGeneratedKeys()) {
                if (generatedKeys.next()) {
                    int generatedId = generatedKeys.getInt(1);
                    System.out.println("Order saved with ID: " + generatedId);
                    return generatedId;
                } else {
                    System.out.println("Creating order failed, no ID obtained.");
                    return -1;
                }
            }




        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }


        return -1;
    }


    public List<Order> findByUserId(int userId) {

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


        try (Connection c = DatabaseConnection.getConnection();
             PreparedStatement pst = c.prepareStatement(quary)){

            pst.setInt(1 , userId);

            try (ResultSet rst = pst.executeQuery()){
                while (rst.next()){
                    Order order = new Order(rst.getInt("id"),
                            rst.getInt("user_id") ,
                            rst.getTimestamp("time").toLocalDateTime(),
                            rst.getDouble("total_price"));

                    result.add(order);

                }


            }


        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }


        return  result;

    }

}