using GraphQL.Types;

namespace Books.Api.GraphQL.Scalars;

/// <summary>
/// GraphQL scalar type for DateOnly values.
/// Serializes as ISO 8601 date string (YYYY-MM-DD).
/// </summary>
public class DateOnlyGraphType : ScalarGraphType
{
    public DateOnlyGraphType()
    {
        Name = "Date";
        Description = "A date without time (ISO 8601 format: YYYY-MM-DD)";
    }

    public override object? ParseLiteral(GraphQLParser.AST.GraphQLValue value)
    {
        if (value is GraphQLParser.AST.GraphQLStringValue stringValue)
        {
            return ParseValue(stringValue.Value.ToString());
        }
        return null;
    }

    public override object? ParseValue(object? value)
    {
        if (value == null) return null;

        if (value is DateOnly dateOnly)
            return dateOnly;

        if (value is string str && DateOnly.TryParse(str, out var parsed))
            return parsed;

        if (value is DateTime dt)
            return DateOnly.FromDateTime(dt);

        return null;
    }

    public override object? Serialize(object? value)
    {
        if (value == null) return null;

        if (value is DateOnly dateOnly)
            return dateOnly.ToString("yyyy-MM-dd");

        if (value is DateTime dt)
            return DateOnly.FromDateTime(dt).ToString("yyyy-MM-dd");

        return value.ToString();
    }
}
