using Core.Enumerations;
using DataProviders;
using DataProviders.Buckets;
using DomainResults.Common;
using DomainResults.Mvc;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using WeatherForecast.Policies;

namespace WeatherForecast.Controllers;

/// <summary>
/// 
/// </summary>
[AllowAnonymous]
[Route("api/[controller]")]
public class FileController : ControllerBase {

  private readonly IAuthorizationService _authorizationService;
  private readonly IImageBucketDataProvider _imageBucketDataProvider;

  /// <summary>
  /// 
  /// </summary>
  /// <param name="authorizationService"></param>
  /// <param name="imageBucketDataProvider"></param>
  public FileController(
    IAuthorizationService authorizationService,
    IImageBucketDataProvider imageBucketDataProvider
  ) {
    _authorizationService = authorizationService;
    _imageBucketDataProvider = imageBucketDataProvider;
  }

  /// <summary>
  /// 
  /// </summary>
  /// <param name="siteId"></param>
  /// <param name="userId"></param>
  /// <param name="file"></param>
  /// <returns></returns>
  [HttpPost("{siteId}/{userId}")]
  public async Task<IActionResult> Post([FromRoute] Guid siteId, [FromRoute] Guid userId, IFormFile file) {

    if (!(file.Length > 0))
      return IDomainResult.Failed().ToActionResult();

    using var ms = new MemoryStream();
    file.CopyTo(ms);

    var newFile = new BucketFile(Guid.NewGuid(), siteId, userId, file.FileName, ms.ToArray(), file.ContentType);

    if ((await _authorizationService.AuthorizeAsync(User, new List<BucketFile> { newFile }, new FileAuthorisationRequirement {
      Action = CrudActions.Create
    })).Succeeded) {
      var result = _imageBucketDataProvider.Upload(newFile);
      return result.ToActionResult();
    }

    return Unauthorized();
  }

  /// <summary>
  /// https://www.c-sharpcorner.com/article/fileresult-in-asp-net-core-mvc2/
  /// </summary>
  /// <param name="siteId"></param>
  /// <param name="userId"></param>
  /// <param name="fileId"></param>
  /// <returns></returns>
  [HttpGet("{siteId}/{userId}/{fileId}")]
  public async Task<IActionResult> Get([FromRoute] Guid siteId, [FromRoute] Guid userId, [FromRoute] Guid fileId) {

    var (file, result) = _imageBucketDataProvider.Download(siteId, userId, fileId);
    if (!result.IsSuccess || file == null)
      return result.ToActionResult();

    if ((await _authorizationService.AuthorizeAsync(User, new List<BucketFile> { file }, new FileAuthorisationRequirement { 
      Action = CrudActions.Read
    })).Succeeded) {
      var stream = new MemoryStream(file.Bytes);
      return new FileStreamResult(stream, file.ContentType) {
        FileDownloadName = file.Name
      };
    }

    return Unauthorized();
  }

  /// <summary>
  /// 
  /// </summary>
  /// <param name="siteId"></param>
  /// <param name="userId"></param>
  /// <param name="fileId"></param>
  /// <returns></returns>
  [HttpDelete("{siteId}/{userId}/{fileId}")]
  public async Task<IActionResult> Delete([FromRoute] Guid siteId, [FromRoute] Guid userId, [FromRoute] Guid fileId) {

    var (file, fileDownloadResult) = _imageBucketDataProvider.Download(siteId, userId, fileId);
    if (!fileDownloadResult.IsSuccess || file == null)
      return fileDownloadResult.ToActionResult();

    if ((await _authorizationService.AuthorizeAsync(User, new List<BucketFile> { file }, new FileAuthorisationRequirement {
      Action = CrudActions.Delete
    })).Succeeded) {
      var result = _imageBucketDataProvider.DeleteOne(siteId, userId, fileId);
      return result.ToActionResult();
    }

    return Unauthorized();
  }
}
