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

namespace AsbCloudWebApi.Controllers;


[ApiController]
[Authorize]
[Route("api/[controller]")]
public class WellCompositeOperationController : ControllerBase
{
    private readonly IWellCompositeOperationService wellCompositeOperationService;
    private readonly IWellService wellService;

    public WellCompositeOperationController(IWellCompositeOperationService wellCompositeOperationService, IWellService wellService)
    {
        this.wellCompositeOperationService = wellCompositeOperationService;
        this.wellService = wellService;
    }

    [HttpGet]
    [ProducesResponseType(typeof(WellCompositeOperationDto), (int)System.Net.HttpStatusCode.OK)]
    public async Task<IActionResult> GetAsync([FromQuery] IEnumerable<int> idsWells, CancellationToken token)
    {
        foreach (var idWell in idsWells)
            if (!await UserHasAccessToWellAsync(idWell, token))
                return Forbid();

        var result = await wellCompositeOperationService.GetAsync(idsWells, token)
            .ConfigureAwait(false);

        return Ok(result);
    }

    protected async Task<bool> UserHasAccessToWellAsync(int idWell, CancellationToken token)
    {
        var idCompany = User.GetCompanyId();
        if (idCompany is not null &&
            await wellService.IsCompanyInvolvedInWellAsync((int)idCompany, idWell, token)
                .ConfigureAwait(false))
            return true;
        return false;
    }
}