using AutoMapper;
using Silk_Road_Api.Models;
using Silk_Road_Api.Repositories;
using Silk_Road_Api.Repositories;
using Silk_Road_Api.ViewModels;

namespace Silk_Road_Api.Services
{
    public class UserService : IUserService
    {
        private readonly IUserRepository _userRepository;
        private readonly IManufacturerRepository _manufacturerRepository;
        private readonly IMapper _mapper;
        public UserService(IUserRepository userRepository, IManufacturerRepository manufacturerRepository, IMapper mapper) {
            _userRepository = userRepository;
            _manufacturerRepository = manufacturerRepository;
            _mapper = mapper;
        }

        public User? LoginUser(string username, string password)
        {
            var user =  _userRepository.GetUserByUsernameAndPassword(username, password);
            if (user == null)
            {
                throw new Exception("Username and password don't match");
            }
            return user;
        }

        public async Task RegisterUser(RegistrationViewModel user)
        {
            var dbUser = _userRepository.GetUserByUsername(user.username);
            if (dbUser != null)
            {
                throw new Exception("Username already taken");
            }
            var company = await _manufacturerRepository.GetManufacturerByName(user.name);
            if (company != 0)
            {
                throw new Exception("Company already has an account associated, please contact support");
            }
            var userToBeAdded = _mapper.Map<User>(user);
            var companyToBeAdded = _mapper.Map<Manufacturer>(user);
            await _manufacturerRepository.AddAsync(companyToBeAdded);
            await _manufacturerRepository.SaveChangesAsync();
            userToBeAdded.companyid =  await _manufacturerRepository.GetManufacturerByName(user.name);
            await _userRepository.AddAsync(userToBeAdded);
            await _userRepository.SaveChangesAsync();
        }
    }
}
