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() {

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

        List<MenuItem> menuItems = new ArrayList<>();

        try (
                Connection connection = DatabaseConnection.getConnection();
                PreparedStatement statement = connection.prepareStatement(sql);
                ResultSet resultSet = statement.executeQuery()
        ) {

            while (resultSet.next()) {

                MenuItem menuItem = new MenuItem();

                menuItem.setId(resultSet.getInt("id"));
                menuItem.setName(resultSet.getString("name"));
                menuItem.setDescription(resultSet.getString("description"));
                menuItem.setPrice(resultSet.getDouble("price"));
                menuItem.setCategory(resultSet.getString("category"));

                menuItems.add(menuItem);
            }

        } catch (SQLException e) {

            System.out.println("Error loading menu items: " + e.getMessage());

        }

        return menuItems;
    }

    public MenuItem findById(int id) {

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

        try (
                Connection connection = DatabaseConnection.getConnection();
                PreparedStatement statement = connection.prepareStatement(sql)
        ) {

            statement.setInt(1, id);

            ResultSet resultSet = statement.executeQuery();

            if (resultSet.next()) {

                MenuItem menuItem = new MenuItem();

                menuItem.setId(resultSet.getInt("id"));
                menuItem.setName(resultSet.getString("name"));
                menuItem.setDescription(resultSet.getString("description"));
                menuItem.setPrice(resultSet.getDouble("price"));
                menuItem.setCategory(resultSet.getString("category"));

                return menuItem;
            }

        } catch (SQLException e) {

            System.out.println("Error finding menu item: " + e.getMessage());

        }

        return null;
    }

}