using GerbilManagerWebAPI.Export;
using Microsoft.EntityFrameworkCore;

namespace GerbilManagerWebAPI.Endpoints
{
    /// <summary>
    /// EXPORT-1: GET /export — komplette Datensicherung als Zip
    /// (export.json voll, CSVs deutsch/Excel-freundlich, LIESMICH.txt; OHNE Fotos).
    /// </summary>
    public static class ExportEndpoints
    {
        public static IEndpointRouteBuilder MapExportEndpoints(this IEndpointRouteBuilder app)
        {
            app.MapGet("/export", async (ApplicationContext db, CancellationToken ct) =>
            {
                var data = new ExportService.ExportData(
                    await db.Gerbils.AsNoTracking().ToListAsync(ct),
                    await db.Litters.AsNoTracking().ToListAsync(ct),
                    await db.Contacts.AsNoTracking().ToListAsync(ct),
                    await db.Enclosures.AsNoTracking().ToListAsync(ct),
                    await db.ColorVarieties.AsNoTracking().ToListAsync(ct),
                    await db.HealthRecords.AsNoTracking().ToListAsync(ct),
                    await db.WeightRecords.AsNoTracking().ToListAsync(ct),
                    await db.GerbilPhotos.AsNoTracking().ToListAsync(ct));

                var today = DateOnly.FromDateTime(DateTime.Now);
                var bytes = ExportService.BuildZip(data, today);
                return Results.File(bytes, "application/zip",
                    $"rennmaus-export-{today:yyyy-MM-dd}.zip");
            })
            .WithTags("Export");

            return app;
        }
    }
}
