using System.Text.Json; using Microsoft.EntityFrameworkCore; using ProposalSystem.Application.DTOs; using ProposalSystem.Application.Interfaces; using ProposalSystem.Domain.Entities; using ProposalSystem.Infrastructure.Data; namespace ProposalSystem.Infrastructure.Services; public class CustomerService : ICustomerService { private readonly ProposalDbContext _db; public CustomerService(ProposalDbContext db) { _db = db; } public async Task> SearchAsync(string? query, CancellationToken ct = default) { var q = _db.Customers.AsQueryable(); if (!string.IsNullOrWhiteSpace(query)) { var search = query.ToLower(); q = q.Where(c => c.Name.ToLower().Contains(search)); } var customers = await q .OrderBy(c => c.Name) .Take(50) .ToListAsync(ct); return customers.Select(c => new CustomerResponse( c.Id, c.Name, DeserializeAddresses(c.Addresses), c.CreatedAt )).ToList(); } public async Task CreateAsync(CreateCustomerRequest request, CancellationToken ct = default) { var now = DateTime.UtcNow; var customer = new Customer { Id = Guid.NewGuid(), Name = request.Name, Addresses = request.Addresses != null ? JsonSerializer.Serialize(request.Addresses) : null, CreatedAt = now, UpdatedAt = now, }; _db.Customers.Add(customer); await _db.SaveChangesAsync(ct); return new CustomerResponse( customer.Id, customer.Name, request.Addresses ?? new List(), customer.CreatedAt ); } private static List DeserializeAddresses(string? json) { if (string.IsNullOrEmpty(json)) return new List(); return JsonSerializer.Deserialize>(json) ?? new List(); } }