using Microsoft.EntityFrameworkCore;
using WebApp.Data;
using WebApp.Entities;
using WebApp.Mapping;


namespace WebApp.Endpoints;

public static class OrganizationsEndpoints
{
    const string GetOrganizationEndpointName = "GetOrganization";

    public static RouteGroupBuilder MapOrganizationsEndpoints(this WebApplication app)
    {
        var group = app.MapGroup("api/organizations")
                                .WithParameterValidation();

        // GET /organizations
        group.MapGet("/",
            async (ApplicationDbContext dbContext, HttpContext httpContext) =>
            await dbContext.Organisations
                           //.Include(Eve => Eve.Organisation)
                           .OrderByDescending(Org => Org.OrganisationId)
                           .Select(Org => Org.ToOrgSummaryDto()) //OrgSummaryDto
                           .AsNoTracking()
                           .ToListAsync());

        // GET /organizations/1
        group.MapGet("/{id}",
            async (int id, ApplicationDbContext dbContext, HttpContext httpContext, GeneralUseHelpers guhf) =>
            {
                Organisation? Org = await dbContext.Organisations.FindAsync(id);

                if (Org is null) return Results.NotFound();

                return Results.Ok(Org.ToOrgSummaryDto()); //OrgSummaryDto
            })
        .WithName(GetOrganizationEndpointName);

        return group;
    }
}
