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 query = "SELECT uid, name, price, category FROM menu_item ORDER BY uid";
        List<MenuItem> items = new ArrayList<>();

        try (Connection conn = DatabaseConnection.getConnection();
             PreparedStatement ps = conn.prepareStatement(query)) {

            ResultSet rs = ps.executeQuery();

            while (rs.next()) {
                MenuItem item = new MenuItem();
                item.setId(rs.getInt("uid"));
                item.setName(rs.getString("name"));
                item.setPrice(rs.getDouble("price"));
                item.setCategory(rs.getString("category"));
                items.add(item);
            }

            return items;

        } catch (SQLException e) {
            System.err.println("Error finding menu items: " + e.getMessage());
            return new ArrayList<>();
        }
    }

    public MenuItem findById(int id) {
        String query = "SELECT uid, name, price, category FROM menu_item WHERE uid = ?";

        try (Connection conn = DatabaseConnection.getConnection();
             PreparedStatement ps = conn.prepareStatement(query)) {

            ps.setInt(1, id);
            ResultSet rs = ps.executeQuery();

            if (rs.next()) {
                MenuItem item = new MenuItem();
                item.setId(rs.getInt("uid"));
                item.setName(rs.getString("name"));
                item.setPrice(rs.getDouble("price"));
                item.setCategory(rs.getString("category"));
                return item;
            }

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

        return null;
    }
}