using System.Text.Json;
using GerbilManagerWebAPI.Dtos;
using GerbilManagerWebAPI.Import;
using GerbilManagerWebAPI.Models;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.EntityFrameworkCore;

namespace GerbilManagerWebAPI.Endpoints
{
    /// <summary>
    /// VERIFIED / PROTECTED OVERRIDES — the breeder's hand-curated "this animal is correct" layer.
    ///   POST   /verified-gerbils/{gerbilId} -> mark "vollständig korrekt": snapshot the full Akte,
    ///          freeze all own fields, apply the freeze immediately. Toggle-on. Optional {note}.
    ///   DELETE /verified-gerbils/{gerbilId} -> remove the override (un-flag / release protection).
    ///          Non-destructive: current values stay; the next ingest makes the animal import-driven again.
    ///   GET    /verified-gerbils            -> all overrides (verified + protected) with drift status.
    ///   GET    /verified-gerbils/{gerbilId} -> single status (badge on the Rennmausakte).
    ///   GET    /verified-gerbils/export     -> canonical golden dump for the committed regression fixture.
    /// Overrides are decoupled from gerbils (loose GerbilId, no FK), so they survive the import
    /// re-ingest wipe and are re-applied on top of the fresh import (the "freeze").
    /// </summary>
    public static class VerifiedGerbilEndpoints
    {
        private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web);

        public static IEndpointRouteBuilder MapVerifiedGerbilEndpoints(this IEndpointRouteBuilder app)
        {
            var group = app.MapGroup("/verified-gerbils").WithTags("VerifiedGerbils");

            group.MapPost("/{gerbilId:guid}", async Task<Results<Ok<VerifiedGerbilDto>, NotFound>> (
                Guid gerbilId, VerifyGerbilInput? input, ApplicationContext db) =>
            {
                var g = await db.Gerbils.FirstOrDefaultAsync(x => x.Id == gerbilId);
                if (g is null) return TypedResults.NotFound();

                var snapshot = await GerbilSnapshotService.BuildSnapshotAsync(db, gerbilId);

                var ov = await db.GerbilOverrides.FirstOrDefaultAsync(o => o.GerbilId == gerbilId);
                if (ov is null)
                {
                    ov = new GerbilOverride { Id = Guid.NewGuid(), GerbilId = gerbilId, OverrideJson = "{}" };
                    db.GerbilOverrides.Add(ov);
                }
                ov.EntityName = g.Name;
                ov.IsVerified = true;
                ov.OverrideJson = GerbilSnapshotService.BuildFreezeJson(g);
                ov.SnapshotJson = snapshot is null ? null : GerbilSnapshotService.SerializeSnapshot(snapshot);
                // Reset the drift cache — recomputed on the next ingest against the fresh import.
                ov.LastImportSnapshotJson = null;
                ov.LastImportDiffJson = null;
                ov.Note = string.IsNullOrWhiteSpace(input?.Note) ? ov.Note : input!.Note!.Trim();
                ov.VerifiedAt ??= DateTimeOffset.UtcNow;
                ov.UpdatedAt = DateTimeOffset.UtcNow;
                await db.SaveChangesAsync();
                return TypedResults.Ok(await ToDtoAsync(db, ov));
            });

            group.MapDelete("/{gerbilId:guid}", async Task<Results<NoContent, NotFound>> (
                Guid gerbilId, ApplicationContext db) =>
            {
                var ov = await db.GerbilOverrides.FirstOrDefaultAsync(o => o.GerbilId == gerbilId);
                if (ov is null) return TypedResults.NotFound();
                db.GerbilOverrides.Remove(ov);
                await db.SaveChangesAsync();
                return TypedResults.NoContent();
            });

            group.MapGet("/", async (ApplicationContext db) =>
            {
                var rows = await db.GerbilOverrides.ToListAsync();
                var existingIds = await db.Gerbils.Select(g => g.Id).ToHashSetAsync();
                var list = new List<VerifiedGerbilDto>();
                foreach (var ov in rows.OrderByDescending(o => o.UpdatedAt))
                    list.Add(await ToDtoAsync(db, ov, existingIds));
                return TypedResults.Ok(list);
            });

            group.MapGet("/export", async (ApplicationContext db) =>
            {
                var rows = await db.GerbilOverrides.Where(o => o.IsVerified).ToListAsync();
                var export = rows
                    .OrderBy(o => o.EntityName, StringComparer.Ordinal)
                    .ThenBy(o => o.GerbilId)
                    .Select(o => new VerifiedGoldenEntry(
                        o.GerbilId, o.EntityName, o.VerifiedAt,
                        GerbilSnapshotService.DeserializeSnapshot(o.SnapshotJson)))
                    .ToList();
                return TypedResults.Ok(export);
            });

            group.MapGet("/{gerbilId:guid}", async Task<Results<Ok<VerifiedGerbilDto>, NotFound>> (
                Guid gerbilId, ApplicationContext db) =>
            {
                var ov = await db.GerbilOverrides.FirstOrDefaultAsync(o => o.GerbilId == gerbilId);
                if (ov is null) return TypedResults.NotFound();
                return TypedResults.Ok(await ToDtoAsync(db, ov));
            });

            return app;
        }

        private static async Task<VerifiedGerbilDto> ToDtoAsync(
            ApplicationContext db, GerbilOverride ov, HashSet<Guid>? existingIds = null)
        {
            var exists = existingIds?.Contains(ov.GerbilId) ?? await db.Gerbils.AnyAsync(g => g.Id == ov.GerbilId);
            var diffs = DeserializeDiff(ov.LastImportDiffJson);
            var status = !exists ? "missing" : (diffs.Count > 0 ? "drifted" : "unchanged");
            return new VerifiedGerbilDto(
                ov.GerbilId, ov.EntityName, ov.IsVerified, status, ov.VerifiedAt, ov.UpdatedAt, ov.Note,
                ExtractFieldKeys(ov.OverrideJson), diffs);
        }

        private static IReadOnlyList<SnapshotDiffDto> DeserializeDiff(string? json)
        {
            if (string.IsNullOrWhiteSpace(json)) return Array.Empty<SnapshotDiffDto>();
            try
            {
                var raw = JsonSerializer.Deserialize<List<SnapshotDiff>>(json, Json) ?? new();
                return raw.Select(d => new SnapshotDiffDto(d.Path, d.GoldenValue, d.OtherValue)).ToList();
            }
            catch (JsonException) { return Array.Empty<SnapshotDiffDto>(); }
        }

        private static IReadOnlyList<string> ExtractFieldKeys(string? overrideJson)
        {
            if (string.IsNullOrWhiteSpace(overrideJson)) return Array.Empty<string>();
            try
            {
                using var doc = JsonDocument.Parse(overrideJson);
                if (doc.RootElement.ValueKind != JsonValueKind.Object) return Array.Empty<string>();
                return doc.RootElement.EnumerateObject().Select(p => p.Name).ToList();
            }
            catch (JsonException) { return Array.Empty<string>(); }
        }
    }
}
