using Data.SeaHavenIndustries; using Microsoft.EntityFrameworkCore; using SeaHaven.DataServices.Interfaces; namespace SeaHaven.DataServices.Implementation; public sealed class AccountOwnerDataService : IAccountOwnerDataService { private readonly ApplicationDbContext _context; public AccountOwnerDataService(ApplicationDbContext context) { _context = context; } public async Task EnsureConfiguredOwnerAsync( string? configuredUserId, CancellationToken cancellationToken) { var ownerId = string.IsNullOrWhiteSpace(configuredUserId) ? null : configuredUserId.Trim(); if (ownerId is not null) { var configuredUserExists = await _context.Users .AsNoTracking() .AnyAsync(user => user.Id == ownerId, cancellationToken); if (!configuredUserExists) throw new InvalidOperationException("The configured account owner user was not found."); } var ownerRows = await _context.Users .Where(user => user.IsAccountOwner || (ownerId != null && user.Id == ownerId)) .ToListAsync(cancellationToken); var changed = false; foreach (var user in ownerRows) { var shouldBeOwner = ownerId is not null && user.Id == ownerId; if (user.IsAccountOwner != shouldBeOwner) { user.IsAccountOwner = shouldBeOwner; changed = true; } } if (changed) await _context.SaveChangesAsync(cancellationToken); return changed; } }