using AutoMapper;
using FluentValidation;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using PARR.API.Contracts.V1;
using PARR.API.Contracts.V1.Requests;
using PARR.API.Contracts.V1.Requests.Queries;
using PARR.API.Contracts.V1.Responses;
using PARR.API.Contracts.V1.Responses.Base;
using PARR.API.Controllers.V1.Base;
using PARR.API.Extensions;
using PARR.API.Services.Interfaces;
using PARR.Core.Repositories.Interfaces;
using PARR.Domain.Common.Pagination;
using PARR.Domain.Common.Roles;
using PARR.Domain.Entities;
using PARR.Domain.Exceptions;

namespace PARR.API.Controllers.V1
{
    /// <summary>
    /// Управление пользователями
    /// </summary>
    [Authorize(Roles = ParrRoles.Administrator.Role)]
    public class UserController : BaseApiController
    {
        private readonly IMapper mapper;
        private readonly IUserRepository userService;
        //private readonly IValidator<UserRequest> validator;
        private readonly IUriService uriService;
        private readonly ILogger<UserController> logger;

        public UserController(
            IMapper mapper,
            IUserRepository userService,
            //IValidator<UserRequest> validator,
            IUriService uriService,
            ILogger<UserController> logger
            )
        {
            this.mapper = mapper;
            this.userService = userService;
            //this.validator = validator;
            this.uriService = uriService;
            this.logger = logger;
        }

        /// <summary>
        /// Список пользователей постранично
        /// </summary>
        /// <param name="paginationQuery"></param>
        /// <returns></returns>
        [HttpGet(ApiRoutes.User.GetAll)]
        public async Task<IActionResult> GetAll([FromQuery] PaginationQuery paginationQuery)
        {
            var paginationFilter = mapper.Map<PaginationFilter>(paginationQuery);

            IQueryable<User> query = userService.Get()
                                        .Include(t => t.Roles).ThenInclude(t => t.Role)
                                        .OrderBy(t => t.Name);

            var users = await userService.GetPage(query, paginationFilter).ToListAsync();

            if (!users.Any())
                return NoContent();

            var userResponse = mapper.Map<List<UserResponse>>(users);
            var paginationResponse = new PagedResponse<UserResponse>(userResponse, true).GetPaginatedProps(paginationFilter, query);

            return Ok(paginationResponse);
        }


        /// <summary>
        /// Получить пользователя по id
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet(ApiRoutes.User.Get)]
        public async Task<IActionResult> GetById([FromRoute] Guid id)
        {
            var user = await userService.Get()
                                .Include(t => t.Roles).ThenInclude(t => t.Role)
                                .FirstOrDefaultAsync(t => t.Id == id);

            if (user == null)
                return NotFound();

            var response = mapper.Map<UserResponse>(user);

            return Ok(new Response<UserResponse>(response, true));
        }


        /// <summary>
        /// Удалить пользователя
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete(ApiRoutes.User.Delete)]
        public async Task<IActionResult> Delete([FromRoute] Guid id)
        {
            var user = await userService.GetAsync(id);

            if (user == null)
                return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = $"Ошибка при удалении пользователя. Не найден пользователь с id: {id}" } }));

            if (!userService.Delete(user) || !await userService.CommitAsync())
                return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = $"Ошибка при удалении пользователя." } }));

            logger.LogInformation($"Пользователь {User.Identity?.Name} удалил пользователя: {user.Id}, {user.Ip}, {user.Name}");

            return NoContent();
        }


        /// <summary>
        /// Создать пользователя
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost(ApiRoutes.User.Create)]
        public async Task<IActionResult> Create([FromBody] UserRequest request)
        {
            //var resultValidate = await validator.ValidateAsync(request);
            //if (!resultValidate.IsValid)
            //    return BadRequest(new Response(resultValidate.Errors));

            var existIp = await userService.Get().FirstOrDefaultAsync(t => t.Ip == request.Ip);
            if (existIp != null)
                //throw new AlreadyExistsException($"Ip {request.Ip} занят другим пользователем.");
                return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { FieldName = nameof(request.Ip), Message = $"Ip {request.Ip} занят другим пользователем." } }));


            var user = new User
            {
                Id = Guid.NewGuid(),
                Ip = request.Ip,
                Name = request.Name,
                Description = request.Description
            };

            if (!await userService.CreateAsync(user) || !await userService.CommitAsync())
                return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = "Ошибка при создани пользователя." } }));

            logger.LogInformation($"Пользователь {User.Identity?.Name} добавил пользователя: {user.Id}, {user.Ip}, {user.Name}");

            var locationUri = uriService.GetUri(ApiRoutes.User.Get, ApiRoutes.User.getParam, user.Id);

            return Created(locationUri, new Response<UserResponse>(mapper.Map<UserResponse>(user), true));
        }


        /// <summary>
        /// Обновить пользователя
        /// </summary>
        /// <param name="id"></param>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPut(ApiRoutes.User.Update)]
        public async Task<IActionResult> Update([FromRoute] Guid id, [FromBody] UserRequest request)
        {
            //var resultValidate = await validator.ValidateAsync(request);
            //if (!resultValidate.IsValid)
            //    return BadRequest(new Response(resultValidate.Errors));

            var orig = await userService.Get()
                                .Include(t => t.Roles).ThenInclude(t => t.Role)
                                .FirstOrDefaultAsync(t => t.Id == id);

            if (orig == null)
                return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = "Ошибка при изменении пользователя." } }));

            //хочет изменить свой ip
            if (orig.Ip != request.Ip)
            {
                var existIp = await userService.Get().FirstOrDefaultAsync(t => t.Ip == request.Ip);
                if (existIp != null)
                    return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { FieldName = nameof(request.Ip), Message = $"Ip {request.Ip} занят другим пользователем." } }));
            }

            orig.Ip = request.Ip;
            orig.Name = request.Name;
            orig.Description = request.Description;

            if (!await userService.CommitAsync())
                return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = "Ошибка при изменении пользователя." } }));

            logger.LogInformation($"Пользователь {User.Identity?.Name} обновил пользователя: {orig.Id}, {orig.Ip}, {orig.Name}");

            return Ok(new Response<UserResponse>(mapper.Map<UserResponse>(orig), true));
        }
    }
}
