package queries

import (
	"bssapp-backend/auth"
	"bssapp-backend/internal/authz"
	"context"
	"fmt"
	"strings"
)

func resolvePiyasaScopeInClause(ctx context.Context, column string) (string, error) {
	claims, ok := auth.GetClaimsFromContext(ctx)
	if !ok || claims == nil {
		return "", fmt.Errorf("unauthorized: claims not found")
	}
	if claims.IsAdmin() {
		return "1=1", nil
	}

	rawCodes := authz.GetPiyasaCodesFromCtx(ctx)
	codes := normalizePiyasaCodes(rawCodes)
	if len(codes) == 0 {
		return "1=0", nil
	}
	return authz.BuildMSSQLPiyasaFilterWithCodes(column, codes), nil
}

func buildPiyasaExistsForCariCode(ctx context.Context, cariCodeExpr string) (string, error) {
	inClause, err := resolvePiyasaScopeInClause(ctx, "PF.CustomerAtt01")
	if err != nil {
		return "", err
	}

	return fmt.Sprintf(`
EXISTS (
	SELECT 1
	FROM CustomerAttributesFilter PF
	WHERE (PF.CurrAccCode = %s OR LEFT(PF.CurrAccCode, 8) = LEFT(%s, 8))
	  AND %s
)`, cariCodeExpr, cariCodeExpr, inClause), nil
}

func normalizePiyasaCodes(codes []string) []string {
	out := make([]string, 0, len(codes))
	seen := make(map[string]struct{}, len(codes))
	for _, c := range codes {
		n := strings.ToUpper(strings.TrimSpace(c))
		if n == "" {
			continue
		}
		if _, ok := seen[n]; ok {
			continue
		}
		seen[n] = struct{}{}
		out = append(out, n)
	}
	return out
}
