using Microsoft.AspNetCore.Mvc;
using System.Collections.Concurrent;

namespace VideoStudy.API.Controllers;

public class ActivationRequest
{
    public string Email { get; set; } = string.Empty;
    public string HardwareId { get; set; } = string.Empty;
}

public class LicenseStatus
{
    public bool IsActive { get; set; }
    public string Message { get; set; } = string.Empty;
    public string Token { get; set; } = string.Empty;
}

[ApiController]
[Route("api/[controller]")]
public class LicenseController : ControllerBase
{
    // In-memory simulation for Phase 4 Demo
    private static readonly ConcurrentDictionary<string, List<string>> _activations = new();

    [HttpPost("activate")]
    public ActionResult<LicenseStatus> Activate([FromBody] ActivationRequest request)
    {
        if (string.IsNullOrWhiteSpace(request.Email) || string.IsNullOrWhiteSpace(request.HardwareId))
        {
            return BadRequest(new LicenseStatus { IsActive = false, Message = "Invalid request" });
        }

        // Simulate database lookup
        if (!_activations.ContainsKey(request.Email))
        {
            _activations[request.Email] = new List<string>();
        }

        var userDevices = _activations[request.Email];

        // Check if device already active
        if (userDevices.Contains(request.HardwareId))
        {
            return Ok(new LicenseStatus { IsActive = true, Message = "Device already activated", Token = GenerateMockToken(request) });
        }

        // Limit to 3 devices
        if (userDevices.Count >= 3)
        {
            return StatusCode(403, new LicenseStatus { IsActive = false, Message = "Activation limit reached (Max 3 devices)" });
        }

        // Activate
        userDevices.Add(request.HardwareId);
        return Ok(new LicenseStatus { IsActive = true, Message = "Activation successful", Token = GenerateMockToken(request) });
    }

    [HttpPost("validate")]
    public ActionResult<bool> Validate([FromBody] string token)
    {
        // Mock validation
        return Ok(!string.IsNullOrEmpty(token) && token.StartsWith("MOCK_JWT_"));
    }

    private string GenerateMockToken(ActivationRequest req)
    {
        return $"MOCK_JWT_{Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(req.Email + req.HardwareId))}";
    }
}
