using Forwarder.Features.AssetMapManagement.CreateAssetMap;
using Forwarder.Repositories;

using Microsoft.AspNetCore.Mvc;

namespace Forwarder.Features.AssetMapManagement;

/// <summary>
/// Контроллер для работы с маппингами.
/// </summary>
[Route("api/asset-maps")]
[ApiController]
public class AssetMapsController(
	IAssetMapRepository assetMapRepository
) : ControllerBase
{
	/// <summary>
	/// Получает список маппингов.
	/// </summary>
	/// <param name="request">Запрос</param>
	/// <param name="cancellationToken">Токен отмены.</param>
	/// <returns>Список маппингов.</returns>
	[HttpGet]
	public async Task<IActionResult> GetList(
		[FromQuery] GetMapListRequest request,
		CancellationToken cancellationToken
	)
	{
		var query = assetMapRepository
			.GetQuery();

		if (request.UseOnlyEmptyAssetId == true)
		{
			query = query
				.Where(x => !x.AssetId.HasValue);
		}

		var result = await assetMapRepository
			.GetTable(query, request, cancellationToken);
		if (result.IsFail)
		{
			return BadRequest(result.Error);
		}

		return Ok(result.Value);
	}

	/// <summary>
	/// Получает маппинг по идентификатору.
	/// </summary>
	/// <param name="id">Идентификатор.</param>
	/// <param name="cancellationToken">Токен отмены.</param>
	/// <returns>Маппинг.</returns>
	[HttpGet("{id:guid}")]
	public async Task<IActionResult> Get(Guid id, CancellationToken cancellationToken)
	{
		var result = await assetMapRepository.Get(id, cancellationToken);
		if (result.IsFail)
		{
			return BadRequest(result.Error);
		}

		return Ok(result.Value);
	}

	[HttpPost]
	public async Task<IActionResult> Create(
		[FromBody] CreateAssetMapRequest request,
		CancellationToken cancellationToken)
	{
		var result = await assetMapRepository.AddAsync(request.Abonent, request.AssetId, cancellationToken);
		if (result.IsFail)
		{
			return BadRequest(result.Error);
		}

		return Created($"/api/asset-maps/{result.Value.Id}", result.Value);
	}

	/// <summary>
	/// Обновляет маппинг.
	/// </summary>
	/// <param name="id">Идентификатор.</param>
	/// <param name="request">Запрос.</param>
	/// <param name="cancellationToken">Токен отмены.</param>
	/// <returns></returns>
	[HttpPut("{id:guid}")]
	public async Task<IActionResult> Update(Guid id,
		[FromBody] UpdateAssetMapRequest request,
		CancellationToken cancellationToken)
	{
		var result = await assetMapRepository.UpdateAsync(id, request.AssetId, cancellationToken);
		if (result.IsFail)
		{
			return BadRequest(result.Error);
		}

		return NoContent();
	}

	/// <summary>
	/// Удаляет маппинг.
	/// </summary>
	/// <param name="id">Идентификатор.</param>
	/// <param name="cancellationToken">Токен отмены.</param>
	/// <returns></returns>
	[HttpDelete("{id:guid}")]
	public async Task<IActionResult> Delete(Guid id,
		CancellationToken cancellationToken)
	{
		var result = await assetMapRepository.DeleteAsync(id, cancellationToken);
		if (result.IsFail)
		{
			return BadRequest(result.Error);
		}

		return NoContent();
	}
}
