using AsbCloudApp.Services;
using AsbCloudDb.Model;
using Mapster;
using System.Linq;
using System.Text.Json;
using Microsoft.EntityFrameworkCore;

namespace AsbCloudInfrastructure.Services
{
    public class LastDataService<Tdto, TModel> : ILastDataService<Tdto> where Tdto : new()
    {
        private readonly IAsbCloudDbContext db;

        public LastDataService(IAsbCloudDbContext db)
        {
            this.db = db;
        }

        public Tdto Get(int idWell, int idCategory)
        {
            var entity = db.LastData.AsNoTracking().FirstOrDefault(e =>
                e.IdWell == idWell && e.IdCategory == idCategory);

            if (entity is null)
                return new Tdto();

            var dto = JsonSerializer.Deserialize<Tdto>(entity.Data.ToString());
            return dto;
        }

        public void Upsert(int idWell, int idCategory, Tdto value)
        {
            var model = value.Adapt<TModel>();

            var entity = db.LastData.AsNoTracking()
                .FirstOrDefault(ld => ld.IdWell == idWell &&
                ld.IdCategory == idCategory);

            if (entity is not null)
            {
                entity.Data = model;
                db.LastData.Update(entity);
            }
            else
            {
                var newLastData = new LastData
                {
                    IdWell = idWell,
                    IdCategory = idCategory,
                    Data = model
                };
                db.LastData.Add(newLastData);
            }

            db.SaveChanges();
        }
    }

}