using AutoMapper;
using DamageAssesment.Api.Locations.Db;
using DamageAssesment.Api.Locations.Interfaces;
using Microsoft.EntityFrameworkCore;

namespace DamageAssesment.Api.Locations.Providers
{
    public class RegionsProvider : IRegionsProvider
    {
        private LocationDbContext locationDbContext;
        private ILogger<RegionsProvider> logger;
        private IMapper mapper;

        public RegionsProvider(LocationDbContext regionDbContext, ILogger<RegionsProvider> logger, IMapper mapper)
        {
            this.locationDbContext = regionDbContext;
            this.logger = logger;
            this.mapper = mapper;
            //SeedData();
        }

        public async Task<(bool IsSuccess, Models.Region Region, string ErrorMessage)> GetRegionByIdAsync(string Id)
        {
            try
            {
                logger?.LogInformation("Get Regions from DB");
                var region = await locationDbContext.Regions.AsNoTracking().FirstOrDefaultAsync(s => s.Id == Id);

                if (region != null)
                {
                    logger?.LogInformation($"RegionId: {region.Id} Items found");
                    var result = mapper.Map<Db.Region, Models.Region>(region);
                    return (true, result, null);
                }
                return (false, null, "Not found");
            }
            catch (Exception ex)
            {
                logger?.LogError(ex.ToString());
                return (false, null, ex.Message);
            }
        }

        public async Task<(bool IsSuccess, IEnumerable<Models.Region> regions, string ErrorMessage)> GetRegionsAsync()
        {
            try
            {
                logger?.LogInformation("Get all Regions from DB");
                var regions = await locationDbContext.Regions.AsNoTracking().ToListAsync();

                if (regions != null)
                {
                    logger?.LogInformation($"{regions.Count} Items(s) found");
                    var result = mapper.Map<IEnumerable<Db.Region>, IEnumerable<Models.Region>>(regions);
                    return (true, result, null);
                }
                return (false, null, "Not found");
            }
            catch (Exception ex)
            {
                logger?.LogError(ex.ToString());
                return (false, null, ex.Message);
            }
        }

        public async Task<(bool IsSuccess, Models.Region Region, string ErrorMessage)> PostRegionAsync(Models.Region region)
        {
            try
            {
                if (region != null)
                {
                    var regions = await locationDbContext.Regions.AsNoTracking().ToListAsync();

                    region.Id = Convert.ToString(regions.Count + 1);
                    locationDbContext.Regions.Add(mapper.Map<Models.Region, Db.Region>(region));
                    locationDbContext.SaveChanges();
                    logger?.LogInformation($"{region} added successfuly");
                    return (true, region, "Successful");
                }
                else
                {
                    logger?.LogInformation($"{region} cannot be added");
                    return (false, null, "Region cannot be added");
                }
            }
            catch (Exception ex)
            {
                logger?.LogError(ex.ToString());
                return (false, null, ex.Message);
            }
        }

        public async Task<(bool IsSuccess, Models.Region Region, string ErrorMessage)> PutRegionAsync(Models.Region region)
        {
            try
            {
                if (region != null)
                {
                    var _region = await locationDbContext.Regions.AsNoTracking().Where(s => s.Id == region.Id).FirstOrDefaultAsync();

                    if (_region != null)
                    {
                        locationDbContext.Regions.Update(mapper.Map<Models.Region, Db.Region>(region));
                        locationDbContext.SaveChanges();
                        return (true, region, "Region updated Successfuly");
                    }
                    else
                    {
                        logger?.LogInformation($"RegionID: {region.Id} Not found");
                        return (false, null, "Not Found");
                    }

                }
                else
                {
                    logger?.LogInformation($"RegionID: {region.Id} Bad Request");
                    return (false, null, "Bad request");
                }
            }
            catch (Exception ex)
            {
                logger?.LogError(ex.ToString());
                return (false, null, ex.Message);
            }
        }

        public async Task<(bool IsSuccess, Models.Region Region, string ErrorMessage)> DeleteRegionAsync(string Id)
        {
            try
            {
                var region = await locationDbContext.Regions.AsNoTracking().Where(x => x.Id == Id).FirstOrDefaultAsync();

                if (region != null)
                {
                    locationDbContext.Regions.Remove(region);
                    locationDbContext.SaveChanges();
                    return (true, mapper.Map<Db.Region, Models.Region>(region), $"RegionId {Id} deleted Successfuly");
                }
                else
                {
                    logger?.LogInformation($"RegionID: {Id} Not found");
                    return (false, null, "Not Found");
                }
            }
            catch (Exception ex)
            {
                logger?.LogError(ex.ToString());
                return (false, null, ex.Message);
            }
        }

        public void SeedData()
        {
            if (!locationDbContext.Regions.Any())
            {
                locationDbContext.Regions.Add(new Db.Region() { Id = "1", Name = "North", Abbreviation = "N" });
                locationDbContext.Regions.Add(new Db.Region() { Id = "2", Name = "South", Abbreviation = "S" });
                locationDbContext.Regions.Add(new Db.Region() { Id = "3", Name = "Central", Abbreviation = "C" });
                locationDbContext.SaveChanges();
            }
        }
    }
}