using System.Text.Json;
using Application.Endpoints;

namespace API.Middlewares;

using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;
using System.Linq;
using Application.Services.Jwt;

public class JwtMiddleware
{
    private readonly RequestDelegate _next;
    private readonly IJwtService _jwtService;
    
    public JwtMiddleware(RequestDelegate next, IJwtService jwtService)
    {
        _next = next;
        _jwtService = jwtService;
    }

    public async Task Invoke(HttpContext context)
    {
        var path = context.Request.Path.ToString().ToLower();

        // Define the paths that should bypass JWT validation
        var bypassPaths = new string[]
        {
            "/api/doctors/login",
            "/api/doctors/register",
            "/api/patients/login",
            "/api/patients/register"
        };

        if (!bypassPaths.Contains(path))
        {
            var token = context.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last();
            if (token != null && _jwtService.ValidateJwtToken(token))
            {
                await _next(context);
            }
            else
            {
                context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                context.Response.ContentType = "application/json";
                var response = new BaseResponse
                {
                    StatusCode = StatusCodes.Status401Unauthorized,
                    Message = "Invalid JWT Token",
                    Data = null
                };
                var responseJson = JsonSerializer.Serialize(response);
                await context.Response.WriteAsync(responseJson);
            }
        }
    }
}