package dev.dao;

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

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 * FROM menu";
        List<MenuItem> result = new ArrayList<>();

        try{

            PreparedStatement st = DatabaseConnection.getConnection().prepareStatement(sql);
            ResultSet rs = st.executeQuery();
            while(rs.next()){
                result.add(new MenuItem(
                        rs.getInt("id"),
                        rs.getString("name"),
                        rs.getString("description"),
                        rs.getDouble("price"),
                        rs.getString("category")
                ));
            }

            st.close();

        } catch (SQLException e) {
            System.err.println("Failed to fetch menu " + e.getMessage());
        }

        return result;
    }

    public MenuItem findById(int id) {

        String sql = "SELECT * FROM menu WHERE id=?";
        MenuItem itemMenu = null;

        try{

            PreparedStatement st = DatabaseConnection.getConnection().prepareStatement(sql);
            st.setInt(1, id);
            ResultSet rs = st.executeQuery();

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

            st.close();

        } catch (SQLException e) {
            System.err.println("Failed to fetch item " + e.getMessage());
        }

        return itemMenu;

    }

}