package packs

import (
	"context"
	_ "embed"
	"encoding/json"
	"log"
	"os"
	"strings"

	apperrors "github.com/nexuscrm/backend/pkg/errors"
)

//go:embed dev_connected_apps.json
var devConnectedAppsJSON []byte

type devConnectedApp struct {
	ClientID string `json:"client_id"`
	Name     string `json:"name"`
	KeyID    string `json:"key_id"`
	Secret   string `json:"secret"`
}

// DevSamplePack seeds dev-only data: test connected apps and future test
// fixtures. Excluded from production and from Verify.
type DevSamplePack struct{}

func (p *DevSamplePack) Name() string      { return "dev-sample" }
func (p *DevSamplePack) Category() Category { return DevSample }

func (p *DevSamplePack) Apply(_ context.Context, deps ApplyDeps) error {
	env := strings.ToLower(strings.TrimSpace(os.Getenv("NEXUS_ENV")))
	if env == "production" || env == "prod" || env == "staging" {
		log.Printf("   ℹ️  Skipping dev-sample pack (NEXUS_ENV=%q)", env)
		return nil
	}

	log.Println("📦 Applying dev-sample pack...")

	var apps []devConnectedApp
	if err := json.Unmarshal(devConnectedAppsJSON, &apps); err != nil {
		return apperrors.NewInternalError("failed to parse dev_connected_apps.json", err)
	}

	for _, app := range apps {
		if err := deps.System.UpsertConnectedApp(context.Background(), app.ClientID, app.Name, app.KeyID, app.Secret); err != nil {
			log.Printf("   ⚠️  Failed to ensure dev connected app %s: %v", app.ClientID, err)
		} else {
			log.Printf("   ✅ Ensured dev connected app: %s", app.ClientID)
		}
	}

	log.Println("✅ dev-sample pack applied")
	return nil
}

// Verify is a no-op for DevSample — it is never included in runtime verification.
func (p *DevSamplePack) Verify(_ context.Context, _ VerifyDeps) error {
	return nil
}
