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

namespace RR3CommunityServer.Controllers;

[ApiController]
[Route("drm/api")]
public class DrmController : ControllerBase
{
    private readonly IDrmService _drmService;
    private readonly ILogger<DrmController> _logger;

    public DrmController(IDrmService drmService, ILogger<DrmController> logger)
    {
        _drmService = drmService;
        _logger = logger;
    }

    [HttpGet("core/getNonce")]
    public async Task<ActionResult<SynergyResponse<DrmNonceResponse>>> GetNonce()
    {
        _logger.LogInformation("GetNonce request");

        var nonce = await _drmService.GenerateNonce();

        var response = new SynergyResponse<DrmNonceResponse>
        {
            resultCode = 0,
            message = "Success",
            data = new DrmNonceResponse
            {
                nonce = nonce,
                expiresAt = DateTimeOffset.UtcNow.AddMinutes(5).ToUnixTimeSeconds()
            }
        };

        return Ok(response);
    }

    [HttpGet("core/getPurchasedItems")]
    public async Task<ActionResult<SynergyResponse<List<PurchasedItem>>>> GetPurchasedItems()
    {
        var synergyId = HttpContext.Items["EAM-USER-ID"]?.ToString() ?? "default";
        _logger.LogInformation("GetPurchasedItems for user: {SynergyId}", synergyId);

        var purchases = await _drmService.GetPurchasedItems(synergyId);

        var response = new SynergyResponse<List<PurchasedItem>>
        {
            resultCode = 0,
            message = "Success",
            data = purchases
        };

        return Ok(response);
    }

    [HttpPost("android/verifyAndRecordPurchase")]
    public async Task<ActionResult<SynergyResponse<object>>> VerifyPurchase([FromBody] PurchaseVerificationRequest request)
    {
        var synergyId = HttpContext.Items["EAM-USER-ID"]?.ToString() ?? "default";
        _logger.LogInformation("VerifyAndRecordPurchase: user={User}, sku={Sku}", synergyId, request.sku);

        var verified = await _drmService.VerifyAndRecordPurchase(synergyId, request);

        var response = new SynergyResponse<object>
        {
            resultCode = verified ? 0 : -1,
            message = verified ? "Purchase verified" : "Purchase verification failed",
            data = new { verified = verified }
        };

        return Ok(response);
    }
}
