using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Monitoring.Controllers;
using Monitoring.Core.Domain.UserSettingsManagement;
using Monitoring.Core.Domain.AssetGroupManagement;
using Monitoring.Models;
using Monitoring.Repositories;

namespace Monitoring.Features.UserSettings;

[Route("api/user-settings")]
[Authorize]
public class UserSettingsController(
	UserSettingsRepository userSettingsRepository
) : BaseController
{
	[HttpGet(Name = "GetUserSettings")]
	[ProducesResponseType<UserSettingsModel>(StatusCodes.Status200OK)]
	[ProducesResponseType(StatusCodes.Status404NotFound)]
	public async Task<IActionResult> GetUserSettings(CancellationToken cancellationToken)
	{
		var settings = await userSettingsRepository.GetByUserId(UserId, cancellationToken);
		
		if (settings is null)
		{
			// Создаем настройки по умолчанию
			settings = await userSettingsRepository.CreateOrUpdate(
				UserId,
				PositioningStrategy.Create("center_of_all_objects"),
				cancellationToken: cancellationToken
			);
		}

		return Ok(UserSettingsModel.FromEntity(settings));
	}

	[HttpPut(Name = "UpdateUserSettings")]
	[ProducesResponseType<UserSettingsModel>(StatusCodes.Status200OK)]
	[ProducesResponseType<string>(StatusCodes.Status400BadRequest)]
	public async Task<IActionResult> UpdateUserSettings(
		[FromBody] UpdateUserSettingsRequest request,
		CancellationToken cancellationToken)
	{
		var positioningStrategy = PositioningStrategy.Create(request.PositioningStrategy);
		
		ManualPosition? manualPosition = null;
		if (request.ManualLatitude.HasValue && request.ManualLongitude.HasValue)
		{
			manualPosition = ManualPosition.Create(request.ManualLatitude.Value, request.ManualLongitude.Value);
		}

		AssetGroupId? assetGroupId = null;
		if (!string.IsNullOrEmpty(request.AssetGroupId))
		{
			assetGroupId = new AssetGroupId(Guid.Parse(request.AssetGroupId));
		}

		var settings = await userSettingsRepository.CreateOrUpdate(
			UserId,
			positioningStrategy,
			manualPosition,
			assetGroupId,
			cancellationToken
		);

		return Ok(UserSettingsModel.FromEntity(settings));
	}
} 