using Managing.Api.Authorization;
using Managing.Api.Models.Requests;
using Managing.Application.Abstractions.Services;
using Managing.Domain.Users;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace Managing.Api.Controllers;
///
/// Provides authentication-related actions, including token creation for user authentication.
///
[ApiController]
[Route("[controller]")]
[Produces("application/json")]
public class UserController : BaseController
{
private IConfiguration _config;
private readonly IJwtUtils _jwtUtils;
private readonly IWebhookService _webhookService;
///
/// Initializes a new instance of the class.
///
/// Configuration settings.
/// Service for user-related operations.
/// Utility for JWT token operations.
/// Service for webhook operations.
public UserController(IConfiguration config, IUserService userService, IJwtUtils jwtUtils, IWebhookService webhookService)
: base(userService)
{
_config = config;
_jwtUtils = jwtUtils;
_webhookService = webhookService;
}
///
/// Creates a JWT token for a user based on the provided login credentials.
///
/// The login request containing user credentials.
/// A JWT token if authentication is successful; otherwise, an Unauthorized result.
[AllowAnonymous]
[HttpPost]
public async Task> CreateToken([FromBody] LoginRequest login)
{
var user = await _userService.Authenticate(login.Name, login.Address, login.Message, login.Signature);
if (user != null)
{
var tokenString = _jwtUtils.GenerateJwtToken(user, login.Address);
return Ok(tokenString);
}
return Unauthorized();
}
///
/// Gets the current user's information.
///
/// The current user's information.
[HttpGet]
public async Task> GetCurrentUser()
{
var user = await base.GetUser();
return Ok(user);
}
///
/// Updates the agent name for the current user.
///
/// The new agent name to set.
/// The updated user with the new agent name.
[HttpPut("agent-name")]
public async Task> UpdateAgentName([FromBody] string agentName)
{
var user = await GetUser();
var updatedUser = await _userService.UpdateAgentName(user, agentName);
return Ok(updatedUser);
}
///
/// Updates the avatar URL for the current user.
///
/// The new avatar URL to set.
/// The updated user with the new avatar URL.
[HttpPut("avatar")]
public async Task> UpdateAvatarUrl([FromBody] string avatarUrl)
{
var user = await GetUser();
var updatedUser = await _userService.UpdateAvatarUrl(user, avatarUrl);
return Ok(updatedUser);
}
///
/// Updates the Telegram channel for the current user.
///
/// The new Telegram channel to set.
/// The updated user with the new Telegram channel.
[HttpPut("telegram-channel")]
public async Task> UpdateTelegramChannel([FromBody] string telegramChannel)
{
var user = await GetUser();
var updatedUser = await _userService.UpdateTelegramChannel(user, telegramChannel);
// Send welcome message to the newly configured telegram channel
if (!string.IsNullOrEmpty(telegramChannel))
{
try
{
var welcomeMessage = $"🎉 **Trading Bot - Welcome!**\n\n" +
$"🎯 **Agent:** {user.Name}\n" +
$"📡 **Channel ID:** {telegramChannel}\n" +
$"⏰ **Setup Time:** {DateTime.UtcNow:MMM dd, yyyy • HH:mm:ss} UTC\n\n" +
$"🔔 **Notification Types:**\n" +
$"• 📈 Position Opens & Closes\n" +
$"• 🤖 Bot configuration changes\n\n" +
$"🚀 **Welcome aboard!** Your trading notifications are now live.";
await _webhookService.SendMessage(welcomeMessage, telegramChannel);
}
catch (Exception ex)
{
// Log the error but don't fail the update operation
Console.WriteLine($"Failed to send welcome message to telegram channel {telegramChannel}: {ex.Message}");
}
}
return Ok(updatedUser);
}
///
/// Tests the Telegram channel configuration by sending a test message.
///
/// A message indicating the test result.
[HttpPost("telegram-channel/test")]
public async Task> TestTelegramChannel()
{
var user = await GetUser();
if (string.IsNullOrEmpty(user.TelegramChannel))
{
return BadRequest("No Telegram channel configured for this user. Please set a Telegram channel first.");
}
try
{
var testMessage = $"🚀 **Trading Bot - Channel Test**\n\n" +
$"🎯 **Agent:** {user.Name}\n" +
$"📡 **Channel ID:** {user.TelegramChannel}\n" +
$"⏰ **Test Time:** {DateTime.UtcNow:MMM dd, yyyy • HH:mm:ss} UTC\n\n" +
$"🔔 **You will receive notifications for:**\n" +
$"• 📈 Position Opens & Closes\n" +
$"• 🤖 Bot configuration changes\n\n" +
$"🎉 **Ready to trade!** Your notifications are now active.";
await _webhookService.SendMessage(testMessage, user.TelegramChannel);
return Ok($"Test message sent successfully to Telegram channel {user.TelegramChannel}. Please check your Telegram to verify delivery.");
}
catch (Exception ex)
{
return StatusCode(500, $"Failed to send test message: {ex.Message}");
}
}
}