package dev.dao;

import dev.model.MenuItem;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class MenuItemDao
{
    private final Connection connection;

    public MenuItemDao(Connection connection) {this.connection = connection;}

    public List<MenuItem> findAll()
    {
        List<MenuItem> items = new ArrayList<>();

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

        try (PreparedStatement ps = connection.prepareStatement(sql);
             ResultSet rs = ps.executeQuery())
        {
            while (rs.next())
            {
                MenuItem item = new MenuItem();

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

                items.add(item);
            }

        }
        catch (SQLException e) {System.out.println("Error fetching menu items: " + e.getMessage());}

        return items;
    }

    public MenuItem findById(int id)
    {
        String sql = "SELECT id, name, description, price, category FROM menu_items WHERE id = ?";

        try (PreparedStatement ps = connection.prepareStatement(sql))
        {

            ps.setInt(1, id);

            try (ResultSet rs = ps.executeQuery())
            {
                if (rs.next())
                {
                    MenuItem item = new MenuItem();

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

                    return item;
                }
            }

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

        return null;
    }
}