package dev.dao;

import dev.model.MenuItem;
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.util.ArrayList;
import java.util.List;

public class MenuItemDao {

    public List<MenuItem> findAll() {

        // TODO:
        // Retrieve all menu items

       // return null;
        List<MenuItem> menuItems = new ArrayList<>();
        String sql = "SELECT id, name, description, price, category FROM menu_items";

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

            while (rs.next()) {
                menuItems.add(mapRowToMenuItem(rs));
            }

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

        return menuItems;
    }

    public MenuItem findById(int id) {

        // TODO:
        // Find menu item by id

        String sql = "SELECT id, name, description, price, category FROM menu_items WHERE id = ?";

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

            stmt.setInt(1, id);

            try (ResultSet rs = stmt.executeQuery()) {
                if (rs.next()) {
                    return mapRowToMenuItem(rs);
                }
            }

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

        return null;
    }
    private MenuItem mapRowToMenuItem(ResultSet rs) throws SQLException {
        int id = rs.getInt("id");
        String name = rs.getString("name");
        String description = rs.getString("description");
        BigDecimal price = rs.getBigDecimal("price");
        String category = rs.getString("category");

        return new MenuItem(id, name, description, price, category);
    }
}
