using AsbCloudApp.Data;
using AsbCloudApp.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Threading;
using System.Threading.Tasks;

namespace AsbCloudWebApi.Controllers
{
    /// <summary>
    /// контроллер с контактной информацией по скважине
    /// </summary>
    [ApiController]
    [Authorize]
    public class WellContactController : ControllerBase
    {
        private readonly IWellContactService wellContactsRepository;
        private readonly IWellService wellService;

        public WellContactController(IWellContactService wellContactsRepository, IWellService wellService)
        {
            this.wellContactsRepository = wellContactsRepository;
            this.wellService = wellService;
        }

        /// <summary>
        /// получение списка типов контактов
        /// </summary>
        /// <param name="idWell">ключ скважины</param>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpGet("api/well/{idWell}/contacts/types")]
        [ProducesResponseType(typeof(IEnumerable<CompanyTypeDto>), (int)System.Net.HttpStatusCode.OK)]
        public async Task<IActionResult> GetTypesAsync(int idWell, CancellationToken token)
        {
            var result = await wellContactsRepository.GetTypesAsync(idWell, token).ConfigureAwait(false);
            return Ok(result);
        }

        /// <summary>
        /// Получение пользователей по типу контакта и ключу скважины
        /// </summary>
        /// <param name="idWell">ключ скважины</param>
        /// <param name="contactTypeId">тип контакта</param>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpGet("api/well/{idWell}/contactType/{contactTypeId}")]
        [ProducesResponseType(typeof(IEnumerable<CompanyWithUsersDto>), (int)System.Net.HttpStatusCode.OK)]
        public async Task<IActionResult> GetAsync(int idWell, int contactTypeId, CancellationToken token)
        {
            if (!await CanUserAccessToWellAsync(idWell, token).ConfigureAwait(false))
                return Forbid();

            var result = await wellContactsRepository.GetAsync(idWell, contactTypeId, token).ConfigureAwait(false);
            return Ok(result);
        }


        /// <summary>
        /// Создание контактов по ключу скважины, типу контакта и ключам пользователей
        /// </summary>
        /// <param name="idWell">ключ скважины</param>
        /// <param name="contactTypeId">ключ типа контакта</param>
        /// <param name="userIds">ключи пользователей</param>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpPost("api/well/{idWell}/contactType/{contactTypeId}")]
        [Permission]
        [ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
        public async Task<IActionResult> UpdateRangeAsync(
                [Range(1, int.MaxValue, ErrorMessage = "Id скважины не может быть меньше 1")] int idWell,
                [Range(1, int.MaxValue, ErrorMessage = "Id типа контакта не может быть меньше 1")] int contactTypeId,
                [FromBody] IEnumerable<int> userIds,
                CancellationToken token)
        {
            if (!await CanUserAccessToWellAsync(idWell, token).ConfigureAwait(false))
                return Forbid();

            var result = await wellContactsRepository.UpdateRangeAsync(idWell, contactTypeId, userIds, token).ConfigureAwait(false);
            return Ok(result);
        }

        private async Task<bool> CanUserAccessToWellAsync(int idWell, CancellationToken token)
        {
            int? idCompany = User.GetCompanyId();
            return idCompany is not null && await wellService.IsCompanyInvolvedInWellAsync((int)idCompany,
                idWell, token).ConfigureAwait(false);
        }

    }
}