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.Responses;
using PARR.API.Contracts.V1.Responses.Base;
using PARR.API.Controllers.V1.Base;
using PARR.Core.Repositories.Interfaces;
using PARR.Core.Services.Shortcodes;
using PARR.Domain.Common.Roles;

namespace PARR.API.Controllers.V1
{
    [Authorize(Roles = ParrRoles.Administrator.Role)]
    public class ShortcodeApplyController : BaseApiController
    {
        private readonly ILogger<ShortcodeController> logger;
        private readonly IShortcodesService shortcodesService;
        private readonly ITemplateRepository templateService;

        public ShortcodeApplyController(
            ILogger<ShortcodeController> logger,
            IShortcodesService shortcodesService,
            ITemplateRepository templateService
            )
        {
            this.logger = logger;
            this.shortcodesService = shortcodesService;
            this.templateService = templateService;
        }


        /// <summary>
        /// Получить список всех переменных составляющих
        /// </summary>
        /// <returns></returns>
        [HttpPost(ApiRoutes.ShortcodeApply.Apply)]
        public async Task<IActionResult> Apply([FromBody] ShortcodeApplyRequest request)
        {
            var template = await templateService.Get()
                                .Include(t => t.Unit)
                                .Include(t => t.UnitsInTemplate)
                                .Include(t => t.Unit)
                                .Include(t => t.Job)
                                    .ThenInclude(t => t!.Group)
                                        .ThenInclude(t => t!.GroupType)
                                .Include(t => t.Job)
                                    .ThenInclude(t => t!.Tnk)
                                .AsNoTracking()
                                .FirstOrDefaultAsync(t => t.Id == request.TemplateId);

            if (template == null)
                return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { FieldName = nameof(request.TemplateId), Message = $"Шаблон имеющий Id = {request.TemplateId} не найден" } }));

            var aplyingShortCodes = await shortcodesService.ApplyShortcodesAsync(request.Content, template);

            var response = new ShortcodeApplyResponse { Content = aplyingShortCodes };

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