package handlers

import (
	"errors"
	"strings"

	mysqldriver "github.com/go-sql-driver/mysql"
	"github.com/gofiber/fiber/v2"

	"wucher/internal/transport/http/jsonapi"
)

type relationFieldError struct {
	Pointer string
	Detail  string
}

func mapOperationRelationError(err error, relationMap map[string]relationFieldError) (int, []jsonapi.ErrorObject, bool) {
	var mysqlErr *mysqldriver.MySQLError
	if !errors.As(err, &mysqlErr) {
		return 0, nil, false
	}

	msg := strings.ToLower(strings.TrimSpace(mysqlErr.Message))
	switch mysqlErr.Number {
	case 1452:
		for token, rel := range relationMap {
			t := strings.ToLower(strings.TrimSpace(token))
			if t != "" && strings.Contains(msg, t) {
				return fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{
					Status: "422",
					Title:  "Validation error",
					Detail: rel.Detail,
					Source: &jsonapi.ErrorSource{Pointer: rel.Pointer},
				}}, true
			}
		}
		return fiber.StatusUnprocessableEntity, []jsonapi.ErrorObject{{
			Status: "422",
			Title:  "Validation error",
			Detail: "referenced relation data was not found",
		}}, true
	case 1451:
		return fiber.StatusConflict, []jsonapi.ErrorObject{{
			Status: "409",
			Title:  "Conflict",
			Detail: "cannot delete because this data is still referenced by other records",
		}}, true
	default:
		return 0, nil, false
	}
}
