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

namespace GerbilManagerWebAPI.Endpoints
{
    /// <summary>
    /// FEAT-13: Zuchtprofil (Verkäufer-Block der Abgabeverträge) — Einzelzeile,
    /// per Migration leer geseedet, von der Züchterin unter /einstellungen gepflegt.
    ///   GET /settings/breeder-profile  -> BreederProfileDto
    ///   PUT /settings/breeder-profile  -> 204
    /// </summary>
    public static class SettingsEndpoints
    {
        public static IEndpointRouteBuilder MapSettingsEndpoints(this IEndpointRouteBuilder app)
        {
            var group = app.MapGroup("/settings").WithTags("Settings");

            group.MapGet("/breeder-profile", async Task<Ok<BreederProfileDto>> (ApplicationContext db) =>
            {
                var s = await LoadAsync(db, track: false);
                return TypedResults.Ok(ToDto(s));
            });

            group.MapPut("/breeder-profile", async Task<NoContent> (BreederProfileDto input, ApplicationContext db) =>
            {
                var s = await LoadAsync(db, track: true);
                s.ZuchtName = input.ZuchtName ?? "";
                s.Name = input.Name ?? "";
                s.Address = input.Address ?? "";
                s.Phone = input.Phone ?? "";
                s.Email = input.Email ?? "";
                s.Homepage = input.Homepage ?? "";
                s.City = input.City ?? "";
                await db.SaveChangesAsync();
                return TypedResults.NoContent();
            });

            return app;
        }

        /// <summary>Die Singleton-Zeile; defensiv neu anlegen, falls sie fehlt.</summary>
        private static async Task<BreederSettings> LoadAsync(ApplicationContext db, bool track)
        {
            var query = track ? db.BreederSettings : db.BreederSettings.AsNoTracking();
            var s = await query.FirstOrDefaultAsync(x => x.Id == BreederSettings.SingletonId);
            if (s is null)
            {
                s = new BreederSettings { Id = BreederSettings.SingletonId };
                db.BreederSettings.Add(s);
                await db.SaveChangesAsync();
            }
            return s;
        }

        internal static BreederProfileDto ToDto(BreederSettings s) =>
            new(s.ZuchtName, s.Name, s.Address, s.Phone, s.Email, s.Homepage, s.City);
    }
}
