using DomainResults.Mvc;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Net.Http.Headers;
using WeatherForecast.Services;

namespace WeatherForecast.Controllers;

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

  private readonly IFileService _fileService;

  /// <summary>
  /// 
  /// </summary>
  /// <param name="fileService"></param>
  public FileController(
    IFileService fileService
  ) {
    _fileService = fileService;
  }

  /// <summary>
  /// 
  /// </summary>
  /// <param name="siteId"></param>
  /// <param name="userId"></param>
  /// <param name="file"></param>
  /// <returns></returns>
  [HttpPost("{siteId}/{userId}")]
  public IActionResult Post([FromRoute] Guid siteId, [FromRoute] Guid userId, IFormFile file) {
    var result = _fileService.Post(siteId, userId, file);
    return result.ToActionResult();
  }

  /// <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 IActionResult Get([FromRoute] Guid siteId, [FromRoute] Guid userid, [FromRoute] Guid fileId) {
    var (file, result) = _fileService.Get(siteId, userid, fileId);

    if (!result.IsSuccess || file == null)
      return result.ToActionResult();

    var stream = new MemoryStream(file.Bytes);
    return new FileStreamResult(stream, file.ContentType) {
      FileDownloadName = file.Name
    };
  }

  /// <summary>
  /// 
  /// </summary>
  /// <param name="siteId"></param>
  /// <param name="userId"></param>
  /// <param name="fileId"></param>
  /// <returns></returns>
  [HttpDelete("{siteId}/{userId}/{fileId}")]
  public IActionResult Delete([FromRoute] Guid siteId, [FromRoute] Guid userId, [FromRoute] Guid fileId) {
    var result = _fileService.Delete(siteId, userId, fileId);
    return result.ToActionResult();
  }
}

