package response

import (
	"strings"

	"github.com/gofiber/fiber/v2"

	"wucher/internal/shared/pkg/apperrorsx"
	"wucher/internal/transport/http/jsonapi"
)

var (
	Write         = jsonapi.Write
	WriteWithMeta = jsonapi.WriteWithMeta
	WriteErrors   = writeErrors
)

func writeErrors(c *fiber.Ctx, status int, errs []jsonapi.ErrorObject) error {
	if detail := collectHTTPErrorDetail(errs); detail != "" {
		c.Locals(apperrorsx.ContextKeyHTTPErrorDetail, detail)
	}
	enriched := apperrorsx.EnrichErrorObjects(status, errs)
	for i := range enriched {
		if shouldPreserveDetail(status, errs[i]) {
			continue
		}
		enriched[i].Detail = apperrorsx.PublicDetail(status)
	}
	return jsonapi.WriteErrors(c, status, enriched)
}

func shouldPreserveDetail(status int, err jsonapi.ErrorObject) bool {
	if status != fiber.StatusUnprocessableEntity {
		return false
	}
	lowerDetail := strings.ToLower(strings.TrimSpace(err.Detail))
	lowerPointer := ""
	if err.Source != nil {
		lowerPointer = strings.ToLower(strings.TrimSpace(err.Source.Pointer))
	}
	return strings.Contains(lowerDetail, "shift_time.") ||
		strings.Contains(lowerDetail, "latitude") ||
		strings.Contains(lowerDetail, "longitude") ||
		strings.Contains(lowerDetail, "coordinates") ||
		strings.Contains(lowerDetail, "twilight") ||
		strings.HasPrefix(lowerPointer, "/path/") ||
		strings.Contains(lowerPointer, "operational_shift_times") ||
		strings.Contains(lowerPointer, "latitude") ||
		strings.Contains(lowerPointer, "longitude") ||
		strings.Contains(lowerPointer, "shift_time")
}

func collectHTTPErrorDetail(errs []jsonapi.ErrorObject) string {
	parts := make([]string, 0, len(errs))
	for i := range errs {
		if detail := strings.TrimSpace(errs[i].Detail); detail != "" {
			parts = append(parts, detail)
		}
	}
	return strings.Join(parts, "; ")
}
