using Freman.Sample.Web.Contracts;
using Freman.Sample.Web.Data;
using Microsoft.EntityFrameworkCore;

namespace Freman.Sample.Web.Endpoints;

public static class NotesEndpoints
{
    public static IEndpointRouteBuilder MapNotesEndpoints(this IEndpointRouteBuilder app)
    {
        var notesApi = app.MapGroup("/api/notes");

        notesApi.MapGet("/", async (AppDbContext db, CancellationToken ct) =>
        {
            var notes = await db.Notes
                .OrderByDescending(n => n.CreatedUtc)
                .Take(50)
                .Select(n => new NoteDto(n.Id, n.Text, n.CreatedUtc))
                .ToListAsync(ct);

            return Results.Ok(notes);
        });

        notesApi.MapPost("/", async (CreateNoteRequest request, AppDbContext db, CancellationToken ct) =>
        {
            var text = (request.Text ?? "").Trim();
            if (string.IsNullOrWhiteSpace(text))
                return Results.BadRequest("Text is required.");

            if (text.Length > 500)
                return Results.BadRequest("Text must be 500 characters or less.");

            var note = new NoteEntity
            {
                Text = text,
                CreatedUtc = DateTime.UtcNow
            };

            db.Notes.Add(note);
            await db.SaveChangesAsync(ct);

            return Results.Created($"/api/notes/{note.Id}", new NoteDto(note.Id, note.Text, note.CreatedUtc));
        });

        notesApi.MapDelete("/{id:int}", async (int id, AppDbContext db, CancellationToken ct) =>
        {
            var note = await db.Notes.FirstOrDefaultAsync(n => n.Id == id, ct);
            if (note is null)
                return Results.NotFound();

            db.Notes.Remove(note);
            await db.SaveChangesAsync(ct);

            return Results.NoContent();
        });

        return app;
    }
}