using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;

using DomainResults.Mvc;

using WeatherForecast.Services;
using WeatherForecast.Models.Blog.Requests;
using WeatherForecast.Policies;
using Core.Enumerations;
using DataProviders.Collections;
using ExtensionMethods;
using DomainResults.Common;
using DomainObjects.Documents;

namespace WeatherForecast.Controllers;

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

  private readonly IAuthorizationService _authorizationService;
  private readonly IBlogCatalogDataProvider _blogCatalogDataProvider;
  private readonly IBlogItemService _blogItemService;

  /// <summary>
  /// Provides functionality to work with items from blog catalog
  /// </summary>
  /// <param name="authorizationService"></param>
  /// <param name="blogCatalogDataProvider"></param>
  /// <param name="blogItemService"></param>
  public BlogItemController(
    IAuthorizationService authorizationService,
    IBlogCatalogDataProvider blogCatalogDataProvider,
    IBlogItemService blogItemService
    ) {
    _authorizationService = authorizationService;
    _blogCatalogDataProvider = blogCatalogDataProvider;
    _blogItemService = blogItemService;
  }

  #region Authless methods
  /// <summary>
  /// 
  /// </summary>
  /// <param name="siteId"></param>
  /// <param name="slug"></param>
  /// <returns></returns>
  [HttpGet("{siteId}")]
  public IActionResult GetSlug([FromRoute] Guid siteId, [FromQuery] string slug) {
    var result = _blogItemService.GetSlug(siteId, slug);
    return result.ToActionResult();
  }
  #endregion


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

    var blogItem = requestData.ToDomainObject();
    blogItem.SiteId = siteId;

    var userId = User?.Identity?.Name?.ToNullableGuid();
    if (userId == null)
      return IDomainResult.Failed().ToActionResult();

    blogItem.Author = userId.Value;

    if ((await _authorizationService.AuthorizeAsync(User, new List<BlogDocument> { blogItem }, new BlogAuthorizationRequirement {
      Action = CrudActions.Create
    })).Succeeded) {
      var result = _blogItemService.Post(blogItem);
      return result.ToActionResult();
    }

    return Unauthorized();
  }

  /// <summary>
  /// Returns full object
  /// </summary>
  /// <returns></returns>
  [HttpGet("{siteId}/{blogId}")]
  public async Task<IActionResult> Get([FromRoute] Guid siteId, [FromRoute] Guid blogId) {

    var (blogItem, getBlogItemResult) = _blogCatalogDataProvider.Get(siteId, blogId);
    if (!getBlogItemResult.IsSuccess || blogItem == null)
      return getBlogItemResult.ToActionResult();

    if ((await _authorizationService.AuthorizeAsync(User, new List<BlogDocument> { blogItem }, new BlogAuthorizationRequirement {
      Action = CrudActions.Read
    })).Succeeded) {
      var result = _blogItemService.Get(blogItem);
      return result.ToActionResult();
    }

    return Unauthorized();
  }

  /// <summary>
  /// 
  /// </summary>
  /// <param name="siteId"></param>
  /// <param name="blogId"></param>
  /// <param name="requestData"></param>
  /// <returns></returns>
  [HttpPut("{siteId}/{blogId}")]
  public async Task<IActionResult> Update([FromRoute] Guid siteId, [FromRoute] Guid blogId, [FromBody] BlogItemRequestModel requestData) {
    
    var (blogItem, getBlogItemResult) = _blogCatalogDataProvider.Get(siteId, blogId);
    if (!getBlogItemResult.IsSuccess || blogItem == null)
      return getBlogItemResult.ToActionResult();

    if ((await _authorizationService.AuthorizeAsync(User, new List<BlogDocument> { blogItem }, new BlogAuthorizationRequirement {
      Action = CrudActions.Update
    })).Succeeded) {
      var result = _blogItemService.Update(blogItem, requestData);
      return result.ToActionResult();
    }
    
    return Unauthorized();
  }

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

    var (blogItem, getBlogItemResult) = _blogCatalogDataProvider.Get(siteId, blogId);
    if (!getBlogItemResult.IsSuccess || blogItem == null)
      return getBlogItemResult.ToActionResult();

    if ((await _authorizationService.AuthorizeAsync(User, new List<BlogDocument> { blogItem }, new BlogAuthorizationRequirement {
      Action = CrudActions.Delete
    })).Succeeded) {
      var result = _blogCatalogDataProvider.Delete(blogItem.Id);
      return result.ToActionResult();
    }

    return Unauthorized();
  }
}
