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.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class MenuItemDao {

    public List<MenuItem> findAll() {

        // TODO:
        // Retrieve all menu items

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

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

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

            while (resultSet.next()) {
                menuItems.add(new MenuItem(
                        resultSet.getInt("id"),
                        resultSet.getString("name"),
                        resultSet.getString("description"),
                        resultSet.getDouble("price"),
                        resultSet.getString("category")
                ));
            }

            return menuItems;

        } catch (SQLException e) {
            System.out.println("Error retrieving menu items: " + e.getMessage());
            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 connection = DatabaseConnection.getConnection();
             PreparedStatement statement = connection.prepareStatement(sql)) {

            statement.setInt(1, id);

            try (ResultSet resultSet = statement.executeQuery()) {

                if (resultSet.next()) {
                    return new MenuItem(
                            resultSet.getInt("id"),
                            resultSet.getString("name"),
                            resultSet.getString("description"),
                            resultSet.getDouble("price"),
                            resultSet.getString("category")
                    );
                }

                return null;
            }

        } catch (SQLException e) {
            System.out.println("Error finding menu item: " + e.getMessage());
            return null;
        }
    }

}