using System.Text.Json;
using System.Text.Json.Serialization;
using API_Access_Control.Handlers;
using API_Access_Control.Models.Requests;
using API_Access_Control.Models.Responses;
using API_Access_Control.Models.Responses.Errors;
using API_Access_Control.Services;
using Microsoft.AspNetCore.Mvc;

namespace API_Access_Control.Endpoints;

public static class Endpoints
{
    private static readonly JsonSerializerOptions _jsonSerializerOptions = new JsonSerializerOptions { NumberHandling = JsonNumberHandling.Strict };

    private static async Task<T?> DeserializeRequest<T>(HttpContext context) where T : class
    {
        try
        {
            return await context.Request.ReadFromJsonAsync<T>(_jsonSerializerOptions);
        }
        catch (JsonException ex)
        {
            Console.WriteLine($"Error deserializing request body: {ex.Message}");
            return null;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error deserializing request body: {ex.Message}");
            return null;
        }
    }

    public static void MapEndpoints(this WebApplication app)
    {
        // Mapping Generate JWT endpoint
        app.MapPost("/jwt/generator", async (HttpContext context, ConsommateurService consommateurService) =>
        {
            var request = await DeserializeRequest<JWTGenerationRequest>(context);

            if (request == null)
            {
                object jsonMsg = new BadRequest
                {
                    Message = "Invalid request body",
                    Details = "callerId (int) or callerSecret (string) are not present or malformed"
                };
                return Results.BadRequest(jsonMsg);
            }
            else
            {
                // Handle JWT generation request
                var result = GeneratorHandler.HandleRequest(request, consommateurService);
                return Results.Ok(result);
            }
        });

        // Mapping Validate JWT endpoint
        app.MapPost("/jwt/validator", async (HttpContext context, ApiService apiService) =>
        {
            var request = await DeserializeRequest<JWTValidationRequest>(context);

            if (request == null)
            {
                object jsonMsg = new BadRequest
                {
                    Message = "Invalid request body",
                    Details = "apiId (int) or apiSecret (string) are not present or malformed"
                };
                return Results.BadRequest(jsonMsg);
            }
            else
            {
                // Handle JWT validation request
                var result = ValidatorHandler.HandleRequest(request, apiService);
                return Results.Ok(result);
            }
        });
    }
}