package dev.dao;

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

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 {

    /**
     * Inserts an order and returns the id the database generated for it.
     * Returns -1 if something went wrong. We let the DB fill in created_at
     * with its DEFAULT, and only send user_id and total_price.
     */
    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());

            stmt.executeUpdate();

            // Read back the auto-generated id (SERIAL primary key).
            try (ResultSet keys = stmt.getGeneratedKeys()) {
                if (keys.next()) {
                    return keys.getInt(1);
                }
            }

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

        return -1;
    }

    public List<Order> findByUserId(int userId) {

        List<Order> orders = new ArrayList<>();

        String sql = "SELECT id, user_id, created_at, total_price " +
                "FROM orders WHERE user_id = ? ORDER BY created_at DESC";

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

            stmt.setInt(1, userId);

            try (ResultSet rs = stmt.executeQuery()) {
                while (rs.next()) {
                    Timestamp ts = rs.getTimestamp("created_at");
                    orders.add(new Order(
                            rs.getInt("id"),
                            rs.getInt("user_id"),
                            ts.toLocalDateTime(),
                            rs.getDouble("total_price")
                    ));
                }
            }

        } catch (SQLException e) {
            System.out.println("Error while loading orders: " + e.getMessage());
        }

        return orders;
    }

}
