using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using MotoresArgentinosV2.Core.DTOs; using MotoresArgentinosV2.Core.Entities; using MotoresArgentinosV2.Core.Interfaces; using MotoresArgentinosV2.Infrastructure.Data; namespace MotoresArgentinosV2.Infrastructure.Services; public class AdSyncService : IAdSyncService { private readonly MotoresV2DbContext _context; private readonly IAvisosLegacyService _legacyService; private readonly ILogger _logger; public AdSyncService(MotoresV2DbContext context, IAvisosLegacyService legacyService, ILogger logger) { _context = context; _legacyService = legacyService; _logger = logger; } public async Task SyncAdToLegacyAsync(int adId) { try { var ad = await _context.Ads .Include(a => a.User) .Include(a => a.Photos) .Include(a => a.Features) .FirstOrDefaultAsync(a => a.AdID == adId); if (ad == null) return false; // Mapeo básico a InsertarAvisoDto var dto = new InsertarAvisoDto { Tipo = "V", // Vehículo NroOperacion = ad.AdID, IdCliente = ad.UserID, NroDoc = ad.User?.Email ?? string.Empty, Razon = ad.User != null ? $"{ad.User.FirstName} {ad.User.LastName}" : "Usuario Desconocido", Email = ad.User?.Email ?? string.Empty, Telefono = ad.ContactPhone ?? string.Empty, Nombreaviso = ad.VersionName ?? "Vehículo sin nombre", IdRubro = 1, // Autos por defecto IdSubrubro = 1, FechaInicio = DateTime.Now, CantDias = 30, ImporteAviso = ad.Price, Tarifa = ad.Price, Destacado = ad.IsFeatured }; // Ejecutar inserción en legacy var result = await _legacyService.InsertarAvisoAsync(dto); if (result) { _logger.LogInformation("Sincronización exitosa del aviso {AdId} al sistema legacy.", adId); // Marcamos el aviso en V2 con la referencia legacy ad.LegacyAdID = ad.AdID; // O el ID real que devuelva el SP si fuera el caso await _context.SaveChangesAsync(); } return result; } catch (Exception ex) { _logger.LogError(ex, "Error sincronizando aviso {AdId} a legacy", adId); return false; } } }