using Microsoft.EntityFrameworkCore; using UtopiaCanteenSystem.Data; using UtopiaCanteenSystem.Models; namespace UtopiaCanteenSystem.Services; /// /// Fetches lunch menu from local SQLite cache (lunch_menu_week → lunch_menu_item → menu_item). /// public class MenuLookupService : IMenuLookupService { private readonly IDbContextFactory _dbFactory; public MenuLookupService(IDbContextFactory dbFactory) { _dbFactory = dbFactory; } public async Task> GetMenuItemsForSiteAsync(int siteIdNumeric, CancellationToken cancellationToken = default) { return await GetMenuItemsForSiteAndDateAsync( siteIdNumeric, DateTime.Today, "NonManagement", "no-active-meal-session", cancellationToken).ConfigureAwait(false); } public async Task> GetMenuItemsForSiteAndDateAsync( int siteIdNumeric, DateTime menuDateLocal, string gradeType, string mealName, CancellationToken cancellationToken = default) { if (siteIdNumeric <= 0) return Array.Empty(); await using var db = await _dbFactory.CreateDbContextAsync(cancellationToken).ConfigureAwait(false); if (!await db.MenuItemCache.AnyAsync(cancellationToken).ConfigureAwait(false)) return Array.Empty(); var menuDate = menuDateLocal.Date; var itemFor = HrmsMenuItemForMapping.FromGradeType(gradeType); var meal = mealName?.Trim() ?? string.Empty; var query = from w in db.LunchMenuWeekCache.AsNoTracking() join li in db.LunchMenuItemCache.AsNoTracking() on w.HrmsId equals li.LunchMenuWeekHrmsId join mi in db.MenuItemCache.AsNoTracking() on li.MenuItemHrmsId equals mi.HrmsId where w.LocationSiteId == siteIdNumeric && w.WeekStartDate != null && w.WeekEndDate != null && menuDate >= w.WeekStartDate.Value.Date && menuDate <= w.WeekEndDate.Value.Date && li.MenuDate != null && li.MenuDate.Value.Date == menuDate && li.MealName == meal && mi.ItemFor == itemFor orderby mi.ItemName select new HrmsMenuItem { MenuItemId = (int)mi.HrmsId, ItemName = mi.ItemName, ItemType = mi.ItemType, Price = mi.Price, MenuDate = li.MenuDate != null ? li.MenuDate.Value.ToString("yyyy-MM-dd") : string.Empty, DayOfWeek = li.DayOfWeek, MealName = li.MealName }; return await query.ToListAsync(cancellationToken).ConfigureAwait(false); } }