using System.Text.Json.Serialization;
using Microsoft.AspNetCore.SignalR;
using Prospect.Server.Api.Hubs;
using Prospect.Server.Api.Services.CloudScript.Models;

// Closed Beta Function

namespace Prospect.Server.Api.Services.CloudScript.Functions;

[CloudScriptFunction("EnterMatchmaking")]
public class EnterMatchmakingFunction : ICloudScriptFunction<FYEnterMatchAzureFunction, FYEnterMatchAzureFunctionResult>
{
    private readonly IHubContext<CycleHub> _hubContext;

    public EnterMatchmakingFunction(IHubContext<CycleHub> hubContext)
    {
        _hubContext = hubContext;
    }

    public async Task<FYEnterMatchAzureFunctionResult> ExecuteAsync(FYEnterMatchAzureFunction request)
    {
        //await _hubContext.Clients.All.SendAsync("OnSquadMatchmakingSuccess", new OnSquadMatchmakingSuccessMessage {
        //    Success = true,
        //    SessionID = request.MapName, // TODO: Need to implement TryGetCompleteSquadInfo and pass squad info
        //    SquadID = request.SquadId,
        //});

        // Dedicated-server mode (2nd preprod): if GAMESERVER_ADDRESS ("host:port") is set, hand
        // the client the real game server to travel to instead of the client-hosted station.
        // Same image as preprod — only this env var flips the deployment type.
        var gameServer = Environment.GetEnvironmentVariable("GAMESERVER_ADDRESS");
        if (!string.IsNullOrEmpty(gameServer))
        {
            var parts = gameServer.Split(':');
            return new FYEnterMatchAzureFunctionResult
            {
                Success = true,
                ErrorMessage = "",
                SingleplayerStation = false,
                Address = parts[0],
                Port = parts.Length > 1 && int.TryParse(parts[1], out var gsPort) ? gsPort : 7777,
                MaintenanceMode = false,
            };
        }

        return new FYEnterMatchAzureFunctionResult
        {
            Success = true,
            ErrorMessage = "",
            SingleplayerStation = true,
            Address = request.MapName,
            MaintenanceMode = false,
            Port = 7777,
        };
    }
}