using System.Text.Json;
using FluentValidation;
using Microsoft.AspNetCore.Http.Json;
using Microsoft.Extensions.Options;
using SatelliteProvider.Common.DTO;

namespace SatelliteProvider.Api.Validators;

// AZ-810: endpoint filter for `POST /api/satellite/upload`. The endpoint is
// `multipart/form-data`, not a plain JSON body, so the standard
// `WithValidation<T>()` filter (which expects an `[FromBody]` argument
// already deserialized by the binder) cannot be used. This filter reads
// the multipart `metadata` form field, deserializes it with the strict
// global `JsonSerializerOptions` (which includes
// `UnmappedMemberHandling.Disallow` from AZ-795), runs the FluentValidation
// rules on `UavTileBatchMetadataPayload`, and adds the cross-field
// alignment check (`metadata.items.Count == files.Count`).
//
// Failures are returned as RFC 7807 `ValidationProblemDetails` matching
// `_docs/02_document/contracts/api/error-shape.md` v1.0.0; error-map keys
// are prefixed with `metadata.` so paths like `items[0].latitude` from
// the per-item validator surface to the caller as
// `errors["metadata.items[0].latitude"]`.
//
// The downstream `IUavTileUploadHandler` retains its own envelope checks
// as a defence-in-depth backstop (also covers callers invoking the
// handler directly in unit tests). When the filter has already validated,
// the handler's checks are no-ops by construction.
public sealed class UavUploadValidationFilter : IEndpointFilter
{
    private const string MetadataKeyPrefix = "metadata.";
    private const string MetadataField = "metadata";
    private const string FilesField = "files";
    private const string MetadataJsonParseError = "`metadata` could not be parsed as JSON.";

    private readonly IValidator<UavTileBatchMetadataPayload> _validator;
    private readonly JsonSerializerOptions _jsonOptions;

    public UavUploadValidationFilter(
        IValidator<UavTileBatchMetadataPayload> validator,
        IOptions<JsonOptions> jsonOptions)
    {
        _validator = validator ?? throw new ArgumentNullException(nameof(validator));
        ArgumentNullException.ThrowIfNull(jsonOptions);
        _jsonOptions = jsonOptions.Value.SerializerOptions;
    }

    public async ValueTask<object?> InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next)
    {
        var request = context.HttpContext.Request;
        if (!request.HasFormContentType)
        {
            return Results.ValidationProblem(new Dictionary<string, string[]>
            {
                [MetadataField] = new[] { "Request must be `multipart/form-data`." },
            });
        }

        var form = await request.ReadFormAsync(context.HttpContext.RequestAborted);
        var metadataField = form[MetadataField].ToString();
        var files = form.Files;

        if (string.IsNullOrWhiteSpace(metadataField))
        {
            return Results.ValidationProblem(new Dictionary<string, string[]>
            {
                [MetadataField] = new[] { "`metadata` form field is required." },
            });
        }

        UavTileBatchMetadataPayload? payload;
        try
        {
            payload = JsonSerializer.Deserialize<UavTileBatchMetadataPayload>(metadataField, _jsonOptions);
        }
        catch (JsonException)
        {
            return Results.ValidationProblem(new Dictionary<string, string[]>
            {
                [MetadataField] = new[] { MetadataJsonParseError },
            });
        }

        if (payload is null)
        {
            return Results.ValidationProblem(new Dictionary<string, string[]>
            {
                [MetadataField] = new[] { "`metadata` must be a non-null JSON object." },
            });
        }

        var result = await _validator.ValidateAsync(payload, context.HttpContext.RequestAborted);
        if (!result.IsValid)
        {
            var prefixed = new Dictionary<string, string[]>(StringComparer.Ordinal);
            foreach (var group in result.ToDictionary())
            {
                prefixed[MetadataKeyPrefix + group.Key] = group.Value;
            }
            return Results.ValidationProblem(prefixed);
        }

        if (payload.Items.Count != files.Count)
        {
            return Results.ValidationProblem(new Dictionary<string, string[]>
            {
                [MetadataKeyPrefix + "items"] = new[]
                {
                    $"`metadata.items` has {payload.Items.Count} entries but `files` has {files.Count}.",
                },
                [FilesField] = new[]
                {
                    $"`files` has {files.Count} entries but `metadata.items` has {payload.Items.Count}.",
                },
            });
        }

        return await next(context);
    }
}
