using System;
using System.Data.Odbc;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;

namespace AS400API.Endpoints;

public static class SystemEndpoints
{
    public static IEndpointRouteBuilder MapRootEndpoints(this IEndpointRouteBuilder app)
    {
        app.MapGet("/", () => Results.Ok(new { name = "AS400API", status = "ok" }));
        return app;
    }

    public static RouteGroupBuilder MapSystemEndpoints(this RouteGroupBuilder group)
    {
        group.MapGet("/v1/health", async (OdbcConnection conn) =>
        {
            try
            {
                await conn.OpenAsync();
                using var cmd = conn.CreateCommand();
                cmd.CommandText = "SELECT CURRENT_DATE AS THE_DATE FROM SYSIBM.SYSDUMMY1";
                using var reader = await cmd.ExecuteReaderAsync();
                if (await reader.ReadAsync())
                {
                    var d = reader.GetDateTime(0);
                    return Results.Ok(new { AS400 = "online", currentDateOnAS400 = d.ToString("yyyy-MM-dd"), timestamp = DateTime.UtcNow });
                }

                return Results.Ok(new { AS400 = "online", note = "no rows" });
            }
            catch (Exception ex)
            {
                return Results.Problem($"AS400 ODBC check failed: {ex.Message}");
            }
        }).AllowAnonymous();

        return group;
    }
}
