package dev.dao;

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

import java.sql.Connection;
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
        List<MenuItem> menuItems = new ArrayList<>();
        try (Connection c = DatabaseConnection.getConnection()) {
            String selectQuery = "SELECT * FROM menu_items";
            try (Statement stmt = c.createStatement();
                 ResultSet rs = stmt.executeQuery(selectQuery)) {

                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) {
           System.err.println("Error in connection with database: " + e.getMessage());
           e.printStackTrace();
       }

        return menuItems;
    }

    public MenuItem findById(int id) {

        // TODO:
        // Find menu item by id

        try (Connection c = DatabaseConnection.getConnection()) {
            String selectQuery = "SELECT * FROM menu_items";
            try (Statement stmt = c.createStatement();
                 ResultSet rs = stmt.executeQuery(selectQuery)) {

                while (rs.next()) {
                    int id_ = rs.getInt("id");
                    if (id_ == id) {
                        String name = rs.getString("name_");
                        String description = rs.getString("description_");
                        double price = rs.getDouble("price");
                        String category = rs.getString("category");
                        return new MenuItem(id, name, description, price, category);
                    }
                }
            }
        }
        catch (SQLException e) {
            System.err.println("Error in connection with database: " + e.getMessage());
            e.printStackTrace();
        }

        return null;
    }

}