using GerbilManagerWebAPI.Common;
using GerbilManagerWebAPI.Dtos;
using GerbilManagerWebAPI.Models;
using Gridify;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.EntityFrameworkCore;

namespace GerbilManagerWebAPI.Endpoints
{
    public static class RecordEndpoints
    {
        public static IEndpointRouteBuilder MapHealthRecordEndpoints(this IEndpointRouteBuilder app)
        {
            var group = app.MapGroup("/health-records").WithTags("HealthRecords");

            // GET /health-records?filter=gerbilId==…
            group.MapGet("/", async ([AsParameters] GridifyParams query, ApplicationContext db) =>
                TypedResults.Ok(await db.HealthRecords.AsNoTracking().ToPagedResultAsync(query, ToDto)));

            group.MapGet("/{id:guid}", async Task<Results<Ok<HealthRecordDto>, NotFound>> (Guid id, ApplicationContext db) =>
            {
                var r = await db.HealthRecords.AsNoTracking().FirstOrDefaultAsync(x => x.Id == id);
                return r is null ? TypedResults.NotFound() : TypedResults.Ok(ToDto(r));
            });

            group.MapPost("/", async (HealthRecordInput input, ApplicationContext db) =>
            {
                var r = new HealthRecord
                {
                    Id = Guid.NewGuid(),
                    GerbilId = input.GerbilId,
                    Date = input.Date,
                    Type = input.Type,
                    Description = input.Description,
                    Veterinarian = input.Veterinarian,
                    CreatedAt = DateTimeOffset.UtcNow,
                };
                db.HealthRecords.Add(r);
                await db.SaveChangesAsync();
                return TypedResults.Created($"/health-records/{r.Id}", ToDto(r));
            });

            group.MapPut("/{id:guid}", async Task<Results<NoContent, NotFound>> (Guid id, HealthRecordInput input, ApplicationContext db) =>
            {
                var r = await db.HealthRecords.FirstOrDefaultAsync(x => x.Id == id);
                if (r is null) return TypedResults.NotFound();
                r.GerbilId = input.GerbilId; r.Date = input.Date; r.Type = input.Type;
                r.Description = input.Description; r.Veterinarian = input.Veterinarian;
                await db.SaveChangesAsync();
                return TypedResults.NoContent();
            });

            group.MapDelete("/{id:guid}", async Task<Results<NoContent, NotFound>> (Guid id, ApplicationContext db) =>
            {
                var r = await db.HealthRecords.FirstOrDefaultAsync(x => x.Id == id);
                if (r is null) return TypedResults.NotFound();
                db.HealthRecords.Remove(r);
                await db.SaveChangesAsync();
                return TypedResults.NoContent();
            });

            return app;
        }

        public static IEndpointRouteBuilder MapWeightRecordEndpoints(this IEndpointRouteBuilder app)
        {
            var group = app.MapGroup("/weight-records").WithTags("WeightRecords");

            group.MapGet("/", async ([AsParameters] GridifyParams query, ApplicationContext db) =>
                TypedResults.Ok(await db.WeightRecords.AsNoTracking().ToPagedResultAsync(query, ToDto)));

            group.MapGet("/{id:guid}", async Task<Results<Ok<WeightRecordDto>, NotFound>> (Guid id, ApplicationContext db) =>
            {
                var r = await db.WeightRecords.AsNoTracking().FirstOrDefaultAsync(x => x.Id == id);
                return r is null ? TypedResults.NotFound() : TypedResults.Ok(ToDto(r));
            });

            group.MapPost("/", async (WeightRecordInput input, ApplicationContext db) =>
            {
                var r = new WeightRecord
                {
                    Id = Guid.NewGuid(),
                    GerbilId = input.GerbilId,
                    Date = input.Date,
                    WeightGrams = input.WeightGrams,
                    Notes = input.Notes,
                };
                db.WeightRecords.Add(r);
                await db.SaveChangesAsync();
                return TypedResults.Created($"/weight-records/{r.Id}", ToDto(r));
            });

            group.MapPut("/{id:guid}", async Task<Results<NoContent, NotFound>> (Guid id, WeightRecordInput input, ApplicationContext db) =>
            {
                var r = await db.WeightRecords.FirstOrDefaultAsync(x => x.Id == id);
                if (r is null) return TypedResults.NotFound();
                r.GerbilId = input.GerbilId; r.Date = input.Date;
                r.WeightGrams = input.WeightGrams; r.Notes = input.Notes;
                await db.SaveChangesAsync();
                return TypedResults.NoContent();
            });

            group.MapDelete("/{id:guid}", async Task<Results<NoContent, NotFound>> (Guid id, ApplicationContext db) =>
            {
                var r = await db.WeightRecords.FirstOrDefaultAsync(x => x.Id == id);
                if (r is null) return TypedResults.NotFound();
                db.WeightRecords.Remove(r);
                await db.SaveChangesAsync();
                return TypedResults.NoContent();
            });

            return app;
        }

        private static HealthRecordDto ToDto(HealthRecord r) =>
            new(r.Id, r.GerbilId, r.Date, r.Type, r.Description, r.Veterinarian, r.CreatedAt);

        private static WeightRecordDto ToDto(WeightRecord r) =>
            new(r.Id, r.GerbilId, r.Date, r.WeightGrams, r.Notes);
    }
}
