package service

import (
	"context"
	"fmt"
	"strings"

	"github.com/gofiber/fiber/v2"
)

// RelationCheck describes a foreign-key style dependency that must exist before processing.
type RelationCheck struct {
	Name   string
	ID     *uint
	Exists func(context.Context, uint) (bool, error)
}

// EnsureRelations validates that each RelationCheck is satisfied, returning consistent Fiber errors.
func EnsureRelations(ctx context.Context, checks ...RelationCheck) error {
	for _, check := range checks {
		if check.ID == nil {
			continue
		}

		exists, err := check.Exists(ctx, *check.ID)
		if err != nil {
			return fiber.NewError(
				fiber.StatusInternalServerError,
				fmt.Sprintf("Failed to check %s", strings.ToLower(check.Name)),
			)
		}
		if !exists {
			return fiber.NewError(
				fiber.StatusNotFound,
				fmt.Sprintf("%s with id %d not found", check.Name, *check.ID),
			)
		}
	}

	return nil
}
