using AsbCloudApp.Data.Trajectory;
using AsbCloudApp.Repositories;
using AsbCloudApp.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using AsbCloudApp.Requests.ExportOptions;
using AsbCloudInfrastructure.Services.Trajectory.Export;

namespace AsbCloudWebApi.Controllers.Trajectory;


/// <summary>
/// Плановые и фактические траектории (загрузка и хранение)
/// </summary>
[ApiController]
[Authorize]
public abstract class TrajectoryController<TDto> : ControllerBase
    where TDto : TrajectoryGeoDto
{
    protected abstract string TemplateFileName { get; }

    private readonly IWellService wellService;
    private readonly TrajectoryExportService<TDto> trajectoryExportService;
    private readonly ITrajectoryRepository<TDto> trajectoryRepository;

    protected TrajectoryController(IWellService wellService,
        TrajectoryExportService<TDto> trajectoryExportService,
        ITrajectoryRepository<TDto> trajectoryRepository)
    {
        this.trajectoryExportService = trajectoryExportService;
        this.wellService = wellService;
        this.trajectoryRepository = trajectoryRepository;
    }

    /// <summary>
    /// Формируем excel файл с текущими строками траектории
    /// </summary>
    /// <param name="idWell">id скважины</param>
    /// <param name="token"> Токен отмены задачи </param>
    /// <returns>Запрашиваемый файл</returns>
    [HttpGet("export")]
    [ProducesResponseType(typeof(PhysicalFileResult), (int)System.Net.HttpStatusCode.OK, "application/octet-stream")]
    [ProducesResponseType(StatusCodes.Status204NoContent)]
    public async Task<IActionResult> ExportAsync([FromRoute] int idWell, CancellationToken token)
    {
        if (!await CanUserAccessToWellAsync(idWell,
            token).ConfigureAwait(false))
            return Forbid();

        var exportOptions = new WellRelatedExportRequest(idWell);
        var (fileName, file) = await trajectoryExportService.ExportAsync(exportOptions, token);
        return File(file, "application/octet-stream", fileName);
    }

    /// <summary>
    /// Получаем список всех строк координат траектории (для клиента)
    /// </summary>
    /// <param name="idWell">ключ скважины</param>
    /// <param name="token"> Токен отмены задачи </param>
    /// <returns>Список добавленных координат траектории</returns>
    [HttpGet]
    public async Task<ActionResult<IEnumerable<TDto>>> GetAsync(int idWell, CancellationToken token)
    {
        if (!await CanUserAccessToWellAsync(idWell,
            token).ConfigureAwait(false))
            return Forbid();
        var result = await trajectoryRepository.GetAsync(idWell, token);
        return Ok(result);
    }

    protected 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);
    }
}