package dev.dao;

import dev.model.Order;

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

public class OrderDao
{
    private final Connection connection;

    public OrderDao(Connection connection) {this.connection = connection;}

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

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

            int affectedRows = ps.executeUpdate();

            if (affectedRows == 0) {return -1;}

            try (ResultSet generatedKeys = ps.getGeneratedKeys())
            {
                if (generatedKeys.next()) {return generatedKeys.getInt(1);}
            }

        }
        catch (SQLException e) {System.out.println("Error 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 (PreparedStatement ps = connection.prepareStatement(sql))
        {
            ps.setInt(1, userId);

            try (ResultSet rs = ps.executeQuery())
            {
                while (rs.next())
                {
                    Order order = new Order();

                    order.setId(rs.getInt("id"));
                    order.setUserId(rs.getInt("user_id"));
                    order.setCreatedAt(rs.getTimestamp("created_at").toLocalDateTime());
                    order.setTotalPrice(rs.getDouble("total_price"));

                    orders.add(order);
                }
            }

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

        return orders;
    }
}