using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Monitoring.Common;
using Monitoring.Controllers;
using Monitoring.Core.Domain.AssetManagement;
using Monitoring.Extensions;
using Monitoring.Features.FaultManagement.GetFaultList;
using Monitoring.Infrastructure.Data;
using Monitoring.Models;

namespace Monitoring.Features.FaultManagement;

[Route("api/faults")]
[Authorize(Roles = Roles.Watcher)]
public class FaultsController(DataContext dataContext) : BaseController
{
	[HttpGet(Name = "GetFaultList")]
	[ProducesResponseType<TableDataResponseModel<FaultModel>>(StatusCodes.Status200OK)]
	public async Task<IActionResult> GetList(
		[FromQuery] GetFaultListRequest request,
		CancellationToken cancellationToken
	)
	{
		var query = dataContext
			.Faults.Include(x => x.Event)
			.Where(x =>
				x.Event.Asset.Groups.Any(x => x.Accesses.Any(x => x.Member.UserId == UserId))
			);
		if (request.AssetId.HasValue)
		{
			var assetId = new AssetId(request.AssetId.Value);
			query = query.Where(x => x.Event.AssetId == assetId);
		}

		var events = await query
			.AsNoTracking()
			.OrderByDescending(x => x.Event.CreatedAt)
			.GetTable(request, FaultModel.FromEntity, cancellationToken);

		return Ok(events);
	}
}
