using Core.Entities; using Core.Utility; using Data; using Microsoft.EntityFrameworkCore; namespace WebApp.Services; /// /// Service for handling EventDefinition-related operations /// public class EventDefinitionService { private readonly AppDbContext _context; public EventDefinitionService(AppDbContext context) { _context = context; } /// /// Processes and normalizes related careers for an EventDefinition. /// Matches existing careers by normalized name (case-insensitive) or creates new ones. /// /// The EventDefinition to process careers for public async Task ProcessRelatedCareersAsync(EventDefinition eventDefinition) { if (string.IsNullOrWhiteSpace(eventDefinition.RelatedCareersText)) { eventDefinition.RelatedCareers.Clear(); return; } var normalizedNames = CareerNormalizer.NormalizeCareerNames(eventDefinition.RelatedCareersText).ToList(); if (!normalizedNames.Any()) { eventDefinition.RelatedCareers.Clear(); return; } // Get all existing careers from database (case-insensitive lookup) var existingCareers = await _context.Careers .Where(c => !string.IsNullOrWhiteSpace(c.Name)) .ToListAsync(); // Build lookup dictionary, handling potential duplicates by taking the first occurrence var careerLookup = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (var career in existingCareers) { var normalizedKey = CareerNormalizer.GetNormalizedKey(career.Name); if (!careerLookup.ContainsKey(normalizedKey)) { careerLookup[normalizedKey] = career; } } var careersToAdd = new List(); foreach (var normalizedName in normalizedNames) { var normalizedKey = CareerNormalizer.GetNormalizedKey(normalizedName); if (careerLookup.TryGetValue(normalizedKey, out var existingCareer)) { // Use existing career (preserve original capitalization) careersToAdd.Add(existingCareer); } else { // Create new career with the normalized name (preserving capitalization from input) var newCareer = new Career { Name = normalizedName }; _context.Careers.Add(newCareer); careersToAdd.Add(newCareer); careerLookup[normalizedKey] = newCareer; } } // Replace the collection eventDefinition.RelatedCareers = careersToAdd; } }