using AsbCloudApp.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Threading;
using System.Threading.Tasks;

namespace AsbCloudWebApi.Controllers
{
    [ApiController]
    [Authorize]
    public abstract class LastDataController<T> : ControllerBase where T : class
    {
        private readonly ILastDataService<T> lastDataService;
        private readonly IWellService wellService;

        public LastDataController(ILastDataService<T> lastDataService, IWellService wellService)
        {
            this.lastDataService = lastDataService;
            this.wellService = wellService;
        }

        [HttpGet]
        public async Task<IActionResult> GetAsync([FromRoute] int idWell, 
            [FromQuery] int idCategory, CancellationToken token = default)
        {
            int? idCompany = User.GetCompanyId();

            if (idCompany is null || !await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, 
                idWell, token).ConfigureAwait(false))
                    return Forbid();

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

        [HttpPost]
        public async Task<IActionResult> PutAsync([FromRoute] int idWell, 
            [FromQuery] int idCategory, T data, CancellationToken token = default)
        {
            int? idCompany = User.GetCompanyId();

            if (idCompany is null || !await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, 
                idWell, token).ConfigureAwait(false))
                    return Forbid();

            await lastDataService.UpsertAsync(idWell, 
                idCategory, data, token).ConfigureAwait(false);
            return Ok();
        }
    }
}