using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Monitoring.Common;
using Monitoring.Controllers;
using Monitoring.Features.Reports.Contracts;

namespace Monitoring.Features.Reports;

/// <summary>
/// Контроллер для работы с отчётами.
/// </summary>
[Route("api/exports")]
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme, Roles = Roles.Watcher)]
public class ExportsController(
	ReportRepository reportRepository,
	FileBuilderFactory fileBuilderFactory
) : BaseController
{
	/// <summary>
	/// Создает файл отчета.
	/// </summary>
	/// <returns>Файл отчета.</returns>
	[HttpPost(Name = "CreateExport")]
	[ProducesResponseType(typeof(byte[]), StatusCodes.Status200OK, "application/octet-stream")]
	[ProducesResponseType<string>(StatusCodes.Status400BadRequest)]
	public async Task<IActionResult> Create(
		CreateExportRequest request,
		CancellationToken cancellationToken
	)
	{
		try
		{
			var dataResult = await reportRepository.Export(request, UserId, cancellationToken);
			if (dataResult.IsFailure)
			{
				return BadRequest(dataResult.Error);
			}

			var fileResult = await fileBuilderFactory.CreateFile(
				request.FileType,
				dataResult.Value,
				cancellationToken
			);
			return fileResult.IsFailure
				? BadRequest(fileResult.Error)
				: File(fileResult.Value, "application/octet-stream");
		}
		catch (Exception ex)
		{
			return BadRequest(ex.Message);
		}
	}
}
