using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using PARR.API.Contracts.V1;
using PARR.API.Contracts.V1.Responses;
using PARR.API.Contracts.V1.Responses.Base;
using PARR.API.Controllers.V1.Base;
using PARR.Core.Repositories.Interfaces.Schedule;
using PARR.Domain.Common.Roles;

namespace PARR.API.Controllers.V1
{
    /// <summary>
    /// Типы заданий из расписания ЕСПП (Регулярно, Еженедельно, Ежемесячно...)
    /// </summary>
    [Authorize(Roles = ParrRoles.Administrator.Role)]
    public class EsppScheduleTypeScheduleController : BaseApiController
    {
        private readonly IMapper mapper;
        private readonly IEsppSchTypeScheduleRepository esppSchTypeScheduleService;

        public EsppScheduleTypeScheduleController(
            IMapper mapper,
            IEsppSchTypeScheduleRepository esppSchTypeScheduleService
            )
        {
            this.mapper = mapper;
            this.esppSchTypeScheduleService = esppSchTypeScheduleService;
        }

        /// <summary>
        /// Список типов заданий расписания ЕСПП
        /// </summary>
        /// <returns></returns>
        [HttpGet(ApiRoutes.EsppScheduleTypeSchedule.GetAll)]
        public async Task<IActionResult> GetAll()
        {
            var objs = await esppSchTypeScheduleService.Get()
                                .OrderBy(t => t.Id)
                                .ToListAsync();

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

            var response = mapper.Map<List<EsppScheduleTypeScheduleResponse>>(objs);

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


        /// <summary>
        /// Тип задания из расписания ЕСПП по ИД, с вложенной структурой
        /// </summary>
        /// <returns></returns>
        [HttpGet(ApiRoutes.EsppScheduleTypeSchedule.Get)]
        public async Task<IActionResult> GetById([FromRoute] int id)
        {
            var obj = await esppSchTypeScheduleService.Get()
                            .Include(t => t.EsppSchTypeConfigs)
                                .ThenInclude(t => t.EsppSchType)
                                    .ThenInclude(t => t.EsppSchTypeValues)
                            .FirstOrDefaultAsync(t => t.Id == id);

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

            var response = mapper.Map<EsppScheduleTypeScheduleWithDataResponse>(obj);

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

    }
}
