package assignmentgen

import (
	"strings"

	"boostai-backend/internal/sqlc"

	"github.com/jackc/pgx/v5/pgtype"
)

func nullableQuestionTopic(topic sqlc.QuestionTopic) sqlc.NullQuestionTopic {
	if topic == "" {
		return sqlc.NullQuestionTopic{}
	}
	return sqlc.NullQuestionTopic{QuestionTopic: topic, Valid: true}
}

func nullableQuestionDifficulty(difficulty sqlc.QuestionDifficulty) sqlc.NullQuestionDifficulty {
	if difficulty == "" {
		return sqlc.NullQuestionDifficulty{}
	}
	return sqlc.NullQuestionDifficulty{QuestionDifficulty: difficulty, Valid: true}
}

func textValue(value string) pgtype.Text {
	trimmed := strings.TrimSpace(value)
	if trimmed == "" {
		return pgtype.Text{}
	}
	return pgtype.Text{String: trimmed, Valid: true}
}

func firstNonEmpty(values ...string) string {
	for _, value := range values {
		if strings.TrimSpace(value) != "" {
			return strings.TrimSpace(value)
		}
	}
	return ""
}

func mergeTags(base []string, extras ...string) []string {
	seen := make(map[string]struct{}, len(base)+len(extras))
	merged := make([]string, 0, len(base)+len(extras))

	appendTag := func(tag string) {
		normalized := strings.TrimSpace(strings.ToLower(tag))
		if normalized == "" {
			return
		}
		if _, exists := seen[normalized]; exists {
			return
		}
		seen[normalized] = struct{}{}
		merged = append(merged, normalized)
	}

	for _, tag := range base {
		appendTag(tag)
	}
	for _, tag := range extras {
		appendTag(tag)
	}

	return merged
}

func questionTopicLabel(topic sqlc.QuestionTopic) string {
	switch topic {
	case sqlc.QuestionTopicPlaceValue:
		return "Place value"
	case sqlc.QuestionTopicArithmetic:
		return "Arithmetic"
	case sqlc.QuestionTopicNegativeNumbers:
		return "Negative numbers"
	case sqlc.QuestionTopicBidmas:
		return "BIDMAS"
	case sqlc.QuestionTopicFractions:
		return "Fractions"
	case sqlc.QuestionTopicAlgebra:
		return "Algebra"
	case sqlc.QuestionTopicGeometry:
		return "Geometry"
	case sqlc.QuestionTopicData:
		return "Data"
	default:
		return "Maths"
	}
}
