package main

import (
	"fmt"
	"os"
	"path/filepath"
	"strings"

	appErrors "github.com/nexuscrm/shared/pkg/errors"
	typedErrors "github.com/nexuscrm/backend/pkg/errors"
)

// ============================================================================
// Error Codes Generation
// ============================================================================

func generateErrorCodes(ctx *genContext, projectRoot string) error {
	var sb strings.Builder

	sb.WriteString("// Code generated by cmd/codegen. DO NOT EDIT.\n")
	sb.WriteString("// Source: shared/pkg/errors/codes.go\n")
	sb.WriteString("// Generated at: " + ctx.timestamp + "\n\n")

	sb.WriteString("export const ERROR_CODES = {\n")

	// Iterate over all error codes from shared package
	for _, code := range appErrors.AllErrorCodes {
		// Key: VALIDATION_ERROR, Value: "VALIDATION_ERROR"
		// Using string(code) to get value
		sb.WriteString(fmt.Sprintf("    %s: '%s',\n", string(code), string(code)))
	}

	sb.WriteString("} as const;\n\n")
	sb.WriteString("export type ErrorCode = typeof ERROR_CODES[keyof typeof ERROR_CODES];\n")

	outPath := filepath.Join(projectRoot, "frontend", "src", "generated-error-codes.ts")
	if err := os.WriteFile(outPath, []byte(sb.String()), 0644); err != nil {
		return typedErrors.NewInternalError("write generated-error-codes.ts", err)
	}
	fmt.Printf("✅ Generated: %s (%d bytes)\n", outPath, sb.Len())
	return nil
}
