using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using PARR.API.Contracts.V1;
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.Core.Common.Helpers;
using PARR.Core.Repositories.Interfaces.Unit;
using PARR.Domain.Common.Pagination;
using PARR.Domain.Common.Roles;
using PARR.Domain.Entities.Unit;

namespace PARR.API.Controllers.V1
{
    [Authorize(Roles = ParrRoles.Administrator.Role)]
    public class UnitController : BaseApiController
    {
        private readonly IMapper mapper;
        private readonly IUnitRepository unitService;

        public UnitController(
            IMapper mapper,
            IUnitRepository unitService
            )
        {
            this.mapper = mapper;
            this.unitService = unitService;
        }


        /// <summary>
        /// Получить список ЭК постранично
        /// </summary>
        /// <param name="paginationQuery"></param>
        /// <returns></returns>
        [HttpGet(ApiRoutes.Unit.GetAll)]
        public async Task<IActionResult> GetAll([FromQuery] PaginationQuery paginationQuery, [FromQuery] HostQuery request)
        {
            var paginationFilter = mapper.Map<PaginationFilter>(paginationQuery);

            IQueryable<Unit> query = unitService.Get()
                                .OrderBy(t => t.Name);

            if (!string.IsNullOrEmpty(request.Mask))
                query = query.Where(t => EF.Functions.Like(t.Name.ToLower(), SqlHelpers.RegexToLike(request.Mask)));

            if (request.IsFull)
                query = query
                            .Include(t => t.UnitValues)
                                .ThenInclude(uv => uv.Value)
                            .Include(tf => tf.UnitValues)
                                .ThenInclude(uv => uv.Field)
                            .Include(p => p.ParentUnits).ThenInclude(t=>t.ParentUnit)
                            .Include(c => c.ChildUnits).ThenInclude(t=>t.ChildUnit);

            var units = await unitService.GetPage(query, paginationFilter).ToListAsync();

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

            //var unitResponse = mapper.Map<List<UnitWithAttributesResponse>>(units);
            //var paginationResponse = new PagedResponse<UnitWithAttributesResponse>(unitResponse, true).GetPaginatedProps(paginationFilter, query);

            var unitResponse = mapper.Map<List<UnitRelationshipsAndAttributesResponse>>(units);
            var paginationResponse = new PagedResponse<UnitRelationshipsAndAttributesResponse>(unitResponse, true).GetPaginatedProps(paginationFilter, query);

            return Ok(paginationResponse);
        }


        /// <summary>
        /// Получить ЭК по id
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet(ApiRoutes.Unit.Get)]
        public async Task<IActionResult> GetById([FromRoute] Guid id)
        {
            var unit = await unitService.Get()
                                .Include(t => t.UnitValues)
                                    .ThenInclude(uv => uv.Value)
                                .Include(tf => tf.UnitValues)
                                    .ThenInclude(uv => uv.Field)
                                .Include(p => p.ParentUnits).ThenInclude(t => t.ParentUnit)
                                .Include(c => c.ChildUnits).ThenInclude(t => t.ChildUnit)
                                .FirstOrDefaultAsync(t => t.Id == id);

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

            //var response = mapper.Map<UnitWithAttributesResponse>(unit);

            //return Ok(new Response<UnitWithAttributesResponse>(response, true));

            var response = mapper.Map<UnitRelationshipsAndAttributesResponse>(unit);

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


    }
}
