package packs

import (
	"context"
	"database/sql"
	_ "embed"
	"encoding/json"
	"fmt"
	"log"

	"github.com/nexuscrm/shared/pkg/models"
)

//go:embed user_page_layout.json
var userPageLayoutJSON []byte

const (
	curatedUserLayoutID     = "curated_User_default"
	curatedUserAssignmentID = "curated_User_assignment_wildcard"
	curatedLayoutSource     = "curated"
)

// parseUserPageLayout decodes the embedded curated layout config and stamps
// the canonical identity fields (Id, ObjectAPIName, Source) so the JSON file
// cannot drift from the values the SQL upsert pins.
func parseUserPageLayout() (models.PageLayout, error) {
	var layout models.PageLayout
	if err := json.Unmarshal(userPageLayoutJSON, &layout); err != nil {
		return layout, fmt.Errorf("parse user_page_layout.json: %w", err)
	}
	layout.ID = curatedUserLayoutID
	layout.ObjectAPIName = "User"
	layout.Source = curatedLayoutSource
	layout.GenerationVersion = 0
	layout.IsCustomized = false
	layout.LayoutVersion = 0
	return layout, nil
}

// applyUserPageLayout installs (or refreshes) the curated User page layout and
// the platform-owned wildcard default when that default is still L1-owned.
// Admin-owned rows/default assignments are preserved.
//
// Issue #656: without a curated layout, the auto-generator dumps every
// discovered physical User column (~165 fields including UserPreferences*)
// into the form. The curated layout below is the SF v63.0 admin
// Setup → New User page projected onto NexusCRM's domain — 33 fields across
// 6 sections. Source='curated' keeps the row out of the auto-regen path
// (metadata_layouts.go:142 only refreshes Source='auto_generated' rows).
//
// Idempotent: every restart converges to the same state for platform-owned
// rows while preserving admin-owned overrides.
func applyUserPageLayout(ctx context.Context, db *sql.DB) error {
	log.Println("🔧 Installing curated User page layout (issue #656)...")

	layout, err := parseUserPageLayout()
	if err != nil {
		return err
	}
	if err := applyCuratedPageLayout(ctx, db, layout, curatedUserAssignmentID, "User"); err != nil {
		return err
	}

	log.Printf("   ✅ Curated User layout installed (%d sections)", len(layout.Sections))
	return nil
}

// verifyCuratedUserLayout is the pod-readiness gate: confirms the layout row
// exists, is not soft-deleted, and is pointed at by the wildcard assignment.
func verifyCuratedUserLayout(db *sql.DB) error {
	return verifyCuratedPageLayout(db, "User", curatedUserLayoutID, "User")
}
