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;

namespace PARR.API.Controllers.V1
{
    /// <summary>
    /// Выходные дни
    /// </summary>
    [Authorize(Roles = ParrRoles.Administrator.Role)]
    public class WeekendController : BaseApiController
    {
        private readonly IMapper mapper;
        private readonly IWeekendDayRepository weekendDayService;
        private readonly IUriService uriService;
        //private readonly IValidator<WeekendRequest> validator;

        public WeekendController(
            IMapper mapper,
            IWeekendDayRepository weekendDayService,
            IUriService uriService,
            IValidator<WeekendRequest> validator
            )
        {
            this.mapper = mapper;
            this.weekendDayService = weekendDayService;
            this.uriService = uriService;
            //this.validator = validator;
        }


        /// <summary>
        /// Получить список выходных дней
        /// </summary>
        /// <returns></returns>
        [HttpGet(ApiRoutes.Weekend.GetAll)]
        public async Task<IActionResult> GetAll([FromQuery] PaginationQuery paginationQuery, [FromQuery] WeekendQuery weekendQuery)
        {
            var paginationFilter = mapper.Map<PaginationFilter>(paginationQuery);

            IQueryable<WeekendDay> query = weekendDayService.Get().OrderBy(t => t.Date);

            if (weekendQuery.StartPeriod.HasValue && weekendQuery.EndPeriod.HasValue)
                query = query.Where(t => t.Date >= weekendQuery.StartPeriod.Value && t.Date <= weekendQuery.EndPeriod);

            var weekends = await weekendDayService.GetPage(query, paginationFilter).ToListAsync();

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

            var response = mapper.Map<List<WeekendResponse>>(weekends);
            var paginationResponse = new PagedResponse<WeekendResponse>(response, true).GetPaginatedProps(paginationFilter, query);

            return Ok(paginationResponse);
        }


        /// <summary>
        /// Получить выходной
        /// </summary>
        /// <returns></returns>
        [HttpGet(ApiRoutes.Weekend.Get)]
        public async Task<IActionResult> Get([FromRoute] DateOnly date)
        {
            var weekend = await weekendDayService.Get().FirstOrDefaultAsync(t => t.Date == date);

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

            var response = mapper.Map<WeekendResponse>(weekend);

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


        /// <summary>
        /// Добавить выходной
        /// </summary>
        /// <returns></returns>
        [HttpPost(ApiRoutes.Weekend.Create)]
        public async Task<IActionResult> Create([FromBody] WeekendRequest request)
        {
            //var resultValidate = await validator.ValidateAsync(request);
            //if (!resultValidate.IsValid)
            //    return BadRequest(new Response(resultValidate.Errors));

            var weekend = new WeekendDay { Id = Guid.NewGuid(), Date = request.WeekendDate };

            if (!await weekendDayService.CreateAsync(weekend) || !await weekendDayService.CommitAsync())
                return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = "Ошибка при добавлении выходного дня." } }));

            var locationUri = uriService.GetUri(ApiRoutes.Weekend.Get, ApiRoutes.Weekend.getParamDate, weekend.Date.ToString());

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


        /// <summary>
        /// Удалить выходной
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        [HttpDelete(ApiRoutes.Weekend.Delete)]
        public async Task<IActionResult> Delete([FromRoute] DateOnly date)
        {
            var weekend = await weekendDayService.Get().FirstOrDefaultAsync(t => t.Date == date);

            if (weekend == null)
                return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = $"Ошибка при удалении выходного дня. Не найден выходной." } }));

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

            return NoContent();
        }
    }
}
