using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Aurora.Core.Domain.Entities;
using Aurora.Core.EntityFramework;
using Aurora.Core.IService;
using Aurora.Core.IService.Dto;
using Aurora.Infrastructure.Response;
using AutoMapper;
using Microsoft.EntityFrameworkCore;

namespace Aurora.Core.Service
{
    public class CategoryService : ICategoryService
    {
        private readonly ApplicationDbContext _dbContext;
        private readonly ApplicationReadonlyDbContext _readonlyDbContext;
        private readonly IMapper _mapper;

        public CategoryService(ApplicationDbContext dbContext,
            ApplicationReadonlyDbContext readonlyDbContext,
            IMapper mapper)
        {
            _mapper = mapper ?? throw new ArgumentNullException(nameof(mapper));

            _dbContext = dbContext;
            _readonlyDbContext = readonlyDbContext;

        }
        public async Task<ResponseModel<List<CategoryDto>>> GetList()
        {
            var list = await _readonlyDbContext.Categories.ToListAsync();
            var dtoList = _mapper.Map<List<CategoryDto>>(list);

            var res = new ResponseModel<List<CategoryDto>>(dtoList);

            return res;
        }

        public async Task<ResponseModel<CategoryDto>> GetById(int id)
        {
            var entity = await _readonlyDbContext.Categories.FirstOrDefaultAsync(m => m.ID == id);
            var dto = _mapper.Map<CategoryDto>(entity);

            var res = new ResponseModel<CategoryDto>(dto);

            return res;
        }

        public async Task<ResponseModel<CategoryDto>> Add(CategoryDto model)
        {
            var entity = _mapper.Map<Category>(model);

            _dbContext.Categories.Add(entity);

            var num = await _dbContext.SaveChangesAsync();

            var dto = _mapper.Map<CategoryDto>(entity);

            var res = new ResponseModel<CategoryDto>(dto);

            return res;
        }
    }
}
