using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Monitoring.Common;
using Monitoring.Controllers;
using Monitoring.Core.Domain.AssetManagement;
using Monitoring.Core.Domain.UserLogManagement;
using Monitoring.Extensions;
using Monitoring.Features.UserLogs.CreateLog;
using Monitoring.Features.UserLogs.GetLogList;
using Monitoring.Infrastructure.Data;
using Monitoring.Models;
using Monitoring.Repositories;
using Monitoring.Services;

namespace Monitoring.Features.UserLogs;

[Route("api/logs")]
[Authorize(Roles = Roles.Watcher)]
public class LogsController(
	DataContext dataContext,
	INotificationService notificationService,
	UsersService usersService,
	AssetRepository assetRepository,
	UserLogRepository userLogRepository
) : BaseController
{
	[HttpGet(Name = "GetLogList")]
	[ProducesResponseType<TableDataResponseModel<UserLogModel>>(StatusCodes.Status200OK)]
	public async Task<IActionResult> GetLogs(
		[FromQuery] GetLogListRequest request,
		CancellationToken cancellationToken
	)
	{
		var assetId = new AssetId(request.AssetId);
		return Ok(
			await dataContext
				.UserLogs.Where(x =>
					x.AssetId == assetId
					&& x.Asset.Groups.Any(x => x.Accesses.Any(x => x.Member.UserId == UserId))
				)
				.OrderByDescending(x => x.CreatedAt)
				.GetTable(request, UserLogModel.FromEntity, cancellationToken)
		);
	}

	[HttpPost(Name = "CreateLog")]
	[ProducesResponseType<UserLogModel>(StatusCodes.Status200OK)]
	[ProducesResponseType<string>(StatusCodes.Status404NotFound)]
	public async Task<IActionResult> Create(
		CreateLogRequest request,
		CancellationToken cancellationToken
	)
	{
		var result = await userLogRepository.Create(
			new AssetId(request.AssetId),
			UserId,
			UserLogInformation.Create(request.Message),
			cancellationToken
		);

		if (result.IsFailure && result.Error == "Asset not found")
		{
			return NotFound(result.Error);
		}

		return Ok(result.Value);
	}
}
