using Microsoft.EntityFrameworkCore; using LittleShop.Data; using LittleShop.Models; using LittleShop.DTOs; namespace LittleShop.Services; public class VariantCollectionService : IVariantCollectionService { private readonly LittleShopContext _context; public VariantCollectionService(LittleShopContext context) { _context = context; } public async Task> GetAllVariantCollectionsAsync() { return await _context.VariantCollections .OrderByDescending(vc => vc.CreatedAt) .Select(vc => new VariantCollectionDto { Id = vc.Id, Name = vc.Name, PropertiesJson = vc.PropertiesJson, IsActive = vc.IsActive, CreatedAt = vc.CreatedAt, UpdatedAt = vc.UpdatedAt }) .ToListAsync(); } public async Task GetVariantCollectionByIdAsync(Guid id) { var collection = await _context.VariantCollections .FirstOrDefaultAsync(vc => vc.Id == id); if (collection == null) return null; return new VariantCollectionDto { Id = collection.Id, Name = collection.Name, PropertiesJson = collection.PropertiesJson, IsActive = collection.IsActive, CreatedAt = collection.CreatedAt, UpdatedAt = collection.UpdatedAt }; } public async Task CreateVariantCollectionAsync(CreateVariantCollectionDto createDto) { var collection = new VariantCollection { Id = Guid.NewGuid(), Name = createDto.Name, PropertiesJson = string.IsNullOrWhiteSpace(createDto.PropertiesJson) ? "[]" : createDto.PropertiesJson, IsActive = true, CreatedAt = DateTime.UtcNow, UpdatedAt = DateTime.UtcNow }; _context.VariantCollections.Add(collection); await _context.SaveChangesAsync(); return new VariantCollectionDto { Id = collection.Id, Name = collection.Name, PropertiesJson = collection.PropertiesJson, IsActive = collection.IsActive, CreatedAt = collection.CreatedAt, UpdatedAt = collection.UpdatedAt }; } public async Task UpdateVariantCollectionAsync(Guid id, UpdateVariantCollectionDto updateDto) { var collection = await _context.VariantCollections.FindAsync(id); if (collection == null) return false; if (!string.IsNullOrEmpty(updateDto.Name)) { collection.Name = updateDto.Name; } if (updateDto.PropertiesJson != null) { collection.PropertiesJson = string.IsNullOrWhiteSpace(updateDto.PropertiesJson) ? "[]" : updateDto.PropertiesJson; } if (updateDto.IsActive.HasValue) { collection.IsActive = updateDto.IsActive.Value; } collection.UpdatedAt = DateTime.UtcNow; await _context.SaveChangesAsync(); return true; } public async Task DeleteVariantCollectionAsync(Guid id) { var collection = await _context.VariantCollections.FindAsync(id); if (collection == null) return false; collection.IsActive = false; collection.UpdatedAt = DateTime.UtcNow; await _context.SaveChangesAsync(); return true; } }