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.Repositories.Interfaces;
using PARR.Domain.Common.Pagination;
using PARR.Domain.Common.Roles;
using PARR.Domain.Entities;

namespace PARR.API.Controllers.V1
{
    /// <summary>
    /// Наряды
    /// </summary>
    [Authorize(Roles = ParrRoles.Administrator.Role)]
    public class OrderController : BaseApiController
    {
        private readonly IMapper mapper;
        private readonly IOrderRepository orderService;

        public OrderController(
             IMapper mapper,
             IOrderRepository orderService
             )
        {
            this.mapper = mapper;
            this.orderService = orderService;
        }


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

            IQueryable<Order> query = orderService.Get()
                .Include(t => t.Template)
                .Include(s => s.OrderStatus)
                .Include(s => s.NextStatus)
                .OrderByDescending(t => t.DateCreated);

            if (filter.TemplateId.HasValue)
                query = query.Where(t => t.TemplateId == filter.TemplateId.Value);

            var orders = await orderService.GetPage(query, paginationFilter).ToListAsync();

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

            var orderResponse = mapper.Map<List<OrderResponse>>(orders);
            var paginationResponse = new PagedResponse<OrderResponse>(orderResponse, true).GetPaginatedProps(paginationFilter, query);

            return Ok(paginationResponse);
        }


        /// <summary>
        /// Получить наряд по id
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet(ApiRoutes.Order.Get)]
        public async Task<IActionResult> Get([FromRoute] Guid id)
        {
            var order = await orderService.Get()
                .Include(t => t.Template)
                .Include(s => s.OrderStatus)
                .Include(s => s.NextStatus)
                .FirstOrDefaultAsync(t => t.Id == id);

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

            var response = mapper.Map<OrderResponse>(order);

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

    }
}
