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

namespace Aurora.Tenant.Service
{
    public class TenantService : ITenantService
    {
        private readonly ApplicationDbContext _dbContext;
        private readonly ApplicationReadonlyDbContext _readonlyDbContext;
        private readonly IMapper _mapper;

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

            _dbContext = dbContext;
            _readonlyDbContext = readonlyDbContext;

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

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

            return res;
        }

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

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

            return res;
        }

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

            _dbContext.Categories.Add(entity);

            var num = await _dbContext.SaveChangesAsync();

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

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

            return res;
        }
    }
}
