// See https://aka.ms/new-console-template for more information
using Forwarder.Data;

using GeoRitmMover.GeoRitm.Data;
using GeoRitmMover.Mover.Data;

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

internal class Worker(
	GeoRitmDbContext sourceDbContext,
	MoverDbContext middlewareDbContext,
	IDataContext destinationDbContext,
	ILogger<Worker> logger
) : BackgroundService
{
	protected override async Task ExecuteAsync(CancellationToken stoppingToken)
	{
		var sourceObjects = await sourceDbContext.Objects
			.ToListAsync(stoppingToken);

		var assetMaps = await middlewareDbContext.Assets
		   .ToListAsync(stoppingToken);

		logger.LogInformation("Try to remove asset maps");
		_ = await destinationDbContext.Maps.ExecuteDeleteAsync(stoppingToken);

		foreach (var sourceObject in sourceObjects)
		{
			if (sourceObject.Imei.HasValue == false)
			{
				continue;
			}

			logger.LogInformation("Try to add asset map for {IMEI}", sourceObject.Imei);

			var map = assetMaps.FirstOrDefault(x => x.From == sourceObject.Id);
			if (map is null)
			{
				continue;
			}

			var abonent = sourceObject.Imei.Value.ToString();
			if (abonent.Length > 8)
			{
				abonent = abonent[^8..];
			}

			Forwarder.Domain.AssetMap destinationAssetMap = new()
			{
				AssetId = map.To.Value,
				Abonent = abonent,
			};

			_ = await destinationDbContext.Maps.AddAsync(destinationAssetMap, stoppingToken);
		}

		logger.LogInformation("Try to save asset maps");
		_ = await destinationDbContext.SaveChangesAsync(stoppingToken);

		logger.LogInformation("Done");
	}
}