using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using PARR.API.Contracts.V1;
using PARR.API.Contracts.V1.Requests;
using PARR.API.Contracts.V1.Requests.Queries;
using PARR.API.Contracts.V1.Responses.Base;
using PARR.API.Contracts.V1.Responses.Statistics;
using PARR.API.Controllers.V1.Base;
using PARR.API.Services.Interfaces;
using PARR.Core.Services.RobotSnapshotServices;
using PARR.Domain.Common.Roles;
using PARR.Domain.DTOs.RobotSnapshotDTO;

namespace PARR.API.Controllers.V1.Statistics
{
    [Authorize]
    public class StatRobotSnapshotController : BaseApiController
    {
        private readonly IRobotSnapshotService robotSnapshotService;
        private readonly IMapper mapper;
        private readonly IClientService clientService;

        public StatRobotSnapshotController(
            IRobotSnapshotService robotSnapshotService,
            IMapper mapper,
            IClientService clientService
            )
        {
            this.robotSnapshotService = robotSnapshotService;
            this.mapper = mapper;
            this.clientService = clientService;
        }


        /// <summary>
        /// Получить снапшоты роботов. 
        /// </summary>
        /// <returns></returns>
        [Authorize(Roles = ParrRoles.Administrator.Role)]
        [HttpGet(ApiRoutes.StatRobotSnapshot.GetAll)]
        public async Task<IActionResult> GetAll([FromQuery] StatRobotSnapshotQuery query)
        {
            var queryDto = mapper.Map<RobotSnapshotQuery>(query);

            var snapshots = await robotSnapshotService.GetAsync(queryDto);

            if (snapshots.Count == 0)
                return NoContent();

            var response = mapper.Map<List<StatRobotSnapshotItemResponse>>(snapshots);

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


        /// <summary>
        /// Отправить снапшот роботов.
        /// Доступ только с ролью "Робот ЕСПП"
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Authorize(Roles = ParrRoles.EsppRobot.Role)]
        [HttpPost(ApiRoutes.StatRobotSnapshot.Create)]
        public async Task<IActionResult> Create([FromBody] StatRobotSnapshotCreateRequest request)
        {
            var obj = new CreateRobotSnapshot(request.TemplateRobotsCount, request.ScheduleRobotsCount, request.MaxRobots, clientService.GetClientIp()?.ToString() ?? "");

            var snapshot = await robotSnapshotService.CreateAsync(obj);

            return Created("", new Response<StatRobotSnapshotItemResponse>(mapper.Map<StatRobotSnapshotItemResponse>(snapshot), true));
        }

    }
}
