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() {

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

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

        try (Connection conn = DatabaseConnection.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql);
             ResultSet rs = stmt.executeQuery()) {

            while (rs.next()) {
                items.add(mapRow(rs));
            }

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

        return items;
    }

    public MenuItem findById(int id) {

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

        try (Connection conn = DatabaseConnection.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setInt(1, id);

            try (ResultSet rs = stmt.executeQuery()) {
                if (rs.next()) {
                    return mapRow(rs);
                }
            }

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

        return null;
    }

    /** Turns the current row of a ResultSet into a MenuItem object. */
    private MenuItem mapRow(ResultSet rs) throws SQLException {
        return new MenuItem(
                rs.getInt("id"),
                rs.getString("name"),
                rs.getString("description"),
                rs.getDouble("price"),
                rs.getString("category")
        );
    }

}
