package dev.dao;

import dev.database.DatabaseConnection;
import dev.model.MenuItem;

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
        List<MenuItem> menuItems = new ArrayList<>();
        String sql = "SELECT * FROM menu_items";

        try(Connection conn = DatabaseConnection.getConnection();
            PreparedStatement stmt = conn.prepareCall(sql);
            ResultSet rs = stmt.executeQuery()) {
            while (rs.next())
            {
                int id = rs.getInt("id");
                String name = rs.getString("name");
                String description = rs.getString("description");
                double price = rs.getDouble("price");
                String category = rs.getString("category");

                MenuItem menuItem = new MenuItem(id, name, description, price, category);
                menuItems.add(menuItem);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return menuItems;
    }

    public MenuItem findById(int id) {

        // TODO:
        // Find menu item by id
        String sql = "SELECT * FROM menu_items WHERE id = ?";

        try(Connection conn = DatabaseConnection.getConnection();
            PreparedStatement stmt = conn.prepareCall(sql);) {
            stmt.setInt(1, id);
            try( ResultSet rs = stmt.executeQuery()) {
                if(rs.next())
                {
                    int itemID = rs.getInt("id");
                    String name = rs.getString("name");
                    String description = rs.getString("description");
                    double price = rs.getDouble("price");
                    String category = rs.getString("category");
                    MenuItem menuItem = new MenuItem(itemID, name, description, price, category);
                    return menuItem;
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return null;
    }

}