using Microsoft.AspNetCore.Mvc;
using RR3CommunityServer.Models;
using RR3CommunityServer.Services;

namespace RR3CommunityServer.Controllers;

[ApiController]
[Route("user/api/android")]
public class UserController : ControllerBase
{
    private readonly IUserService _userService;
    private readonly ISessionService _sessionService;
    private readonly ILogger<UserController> _logger;

    public UserController(IUserService userService, ISessionService sessionService, ILogger<UserController> logger)
    {
        _userService = userService;
        _sessionService = sessionService;
        _logger = logger;
    }

    [HttpGet("getDeviceID")]
    public async Task<ActionResult<SynergyResponse<DeviceIdResponse>>> GetDeviceId(
        [FromQuery] string? deviceId,
        [FromQuery] string hardwareId = "")
    {
        _logger.LogInformation("GetDeviceID request: existing={Existing}, hardware={Hardware}", deviceId, hardwareId);

        var newDeviceId = await _userService.GetOrCreateDeviceId(deviceId, hardwareId);
        var synergyId = await _userService.GetOrCreateSynergyId(newDeviceId);
        var sessionId = await _sessionService.CreateSession(synergyId);

        var response = new SynergyResponse<DeviceIdResponse>
        {
            resultCode = 0,
            message = "Success",
            data = new DeviceIdResponse
            {
                deviceId = newDeviceId,
                synergyId = synergyId,
                timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds()
            }
        };

        return Ok(response);
    }

    [HttpGet("validateDeviceID")]
    public async Task<ActionResult<SynergyResponse<object>>> ValidateDeviceId([FromQuery] string deviceId)
    {
        _logger.LogInformation("ValidateDeviceID: {DeviceId}", deviceId);

        var result = await _userService.ValidateDeviceId(deviceId);

        var response = new SynergyResponse<object>
        {
            resultCode = result == "valid" ? 0 : -1,
            message = result == "valid" ? "Device validated" : "Device not found",
            data = new { status = result }
        };

        return Ok(response);
    }

    [HttpGet("getAnonUid")]
    public async Task<ActionResult<SynergyResponse<AnonUidResponse>>> GetAnonUid()
    {
        _logger.LogInformation("GetAnonUid request");

        var anonUid = await _userService.GetOrCreateAnonUid();

        var response = new SynergyResponse<AnonUidResponse>
        {
            resultCode = 0,
            message = "Success",
            data = new AnonUidResponse
            {
                anonUid = anonUid,
                expiresAt = DateTimeOffset.UtcNow.AddDays(30).ToUnixTimeSeconds()
            }
        };

        return Ok(response);
    }
}
