package layoutauthoringv1

import (
	"context"
	"testing"
	"time"
)

func deadlineContext(t *testing.T) context.Context {
	t.Helper()
	ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
	t.Cleanup(cancel)
	return ctx
}

func pointer[T any](value T) *T { return &value }

func nullValue() Value { return Value{Kind: ValueNull} }

func stringValue(value string) Value {
	return Value{Kind: ValueString, String: pointer(value)}
}

func boolValue(value bool) Value {
	return Value{Kind: ValueBoolean, Boolean: pointer(value)}
}

func decimalValue(value string) Value {
	return Value{Kind: ValueDecimal, Decimal: pointer(value)}
}

func validDocument() LayoutDocument {
	body := "Review the linked record"
	secondaryLabel := "via Parent"
	tabID := "details"
	componentName := "summary-card"
	fieldsKind := "Fields"
	componentKind := "Component"
	condition := "Status == 'Open'"
	position := "banner"
	reason := "Locked while processing"
	icon := "utility:edit"
	targetObject := "Contact"
	actionComponent := "edit-dialog"
	configObject := []NamedValue{
		{Name: "enabled", Value: boolValue(true)},
		{Name: "threshold", Value: decimalValue("12.50")},
	}
	configList := []Value{stringValue("compact"), Value{Kind: ValueObject, Object: &configObject}}
	return LayoutDocument{
		LayoutID:      "layout-main",
		ObjectID:      "Account",
		Name:          "Main Layout",
		Kind:          "Detail",
		LayoutVersion: 7,
		CompactFields: []string{"Name", "Amount"},
		Tabs:          []string{"details", "activity"},
		Sections: []LayoutSection{
			{
				SectionID: "section-main", Label: "Main", TabID: &tabID, Kind: &fieldsKind, Columns: 2,
				ComponentConfiguration: []NamedValue{},
				Fields:                 []string{"Name", "OwnerId.Name"},
				FieldLabels: []FieldLabel{
					{FieldReference: "Name", Label: "Account name"},
					{FieldReference: "Orphaned__c", Label: "Retained orphan"},
				},
				FieldBehaviors: []FieldBehaviorGroup{
					{FieldReference: "Name", Behaviors: pointer([]FieldBehavior{
						{Mode: "Create", Behavior: "  Required  "},
						{Mode: "quickCreate", Behavior: "shown"},
					})},
					{FieldReference: "Orphaned__c", Behaviors: pointer([]FieldBehavior{
						{Mode: "Edit", Behavior: "hidden"},
					})},
				},
				VisibilityCondition: &condition,
			},
			{
				SectionID: "section-component", Label: "Summary", Kind: &componentKind, ComponentName: &componentName,
				ComponentConfiguration: []NamedValue{{Name: "appearance", Value: Value{Kind: ValueList, List: &configList}}},
				Columns:                1, Fields: []string{}, FieldLabels: []FieldLabel{}, FieldBehaviors: []FieldBehaviorGroup{},
			},
		},
		RelatedLists: []RelatedList{{
			RelatedListID: "contacts-parent", Label: "Contacts", SecondaryLabel: secondaryLabel,
			ObjectID: "Contact", LookupFieldID: "ParentId", FieldIDs: []string{"Name", "Email"},
			PrefillMappings: []PrefillMapping{{TargetFieldID: "ParentId", SourceFieldID: "Id"}},
		}},
		RecordPanels: []RecordPanel{{
			PanelID: "panel-summary", RendererID: "summary", Position: "header-banner", Order: 1,
			VisibilityCondition:   position,
			RendererConfiguration: []NamedValue{{Name: "density", Value: stringValue("compact")}},
		}},
		HeaderActions: ActionPlacement{Authored: true, Actions: []LayoutAction{{
			Name: "Edit", Label: "Edit", Kind: "Standard", Icon: &icon, TargetObjectID: &targetObject,
			Component: &actionComponent, VisibilityCondition: &condition,
			Configuration: []NamedValue{{Name: "dialog", Value: stringValue("wide")}},
			Extensions: []NamedValue{
				{Name: "description", Value: stringValue("Edit this record")},
				{Name: "flowName", Value: stringValue("Edit_Account")},
			},
		}}},
		QuickActions: ActionPlacement{Authored: true, Actions: []LayoutAction{}},
		RecordStates: []RecordStateRule{{
			RuleID: "state-open", Condition: "Status == 'Open'", Priority: 10,
			Banner: &RecordStateBanner{Severity: "info", Title: "Open", Body: body, LinkIDs: []string{"parent-link"}},
			Links: []RecordStateLink{{
				LinkID: "parent-link", Label: "Parent", ReferenceFieldID: "ParentId",
				ObjectID: "Account", Placement: "banner",
			}},
			ActionOverrides: []RecordStateActionOverride{{ActionKey: "host:delete", Mode: "disable", Reason: reason}},
			ReadOnly:        &RecordStateReadOnly{Enabled: true, Reason: reason},
		}},
		PrimaryHeaderActions: []string{"host:edit", "standard-action:Clone"},
	}
}

func preserveChanges() LayoutDocumentChanges {
	return LayoutDocumentChanges{
		Name:                 Change[string]{Mode: ChangePreserve},
		Kind:                 Change[string]{Mode: ChangePreserve},
		LayoutVersion:        Change[uint32]{Mode: ChangePreserve},
		CompactFields:        Change[[]string]{Mode: ChangePreserve},
		Tabs:                 Change[[]string]{Mode: ChangePreserve},
		Sections:             Change[[]LayoutSection]{Mode: ChangePreserve},
		RelatedLists:         Change[[]RelatedList]{Mode: ChangePreserve},
		RecordPanels:         Change[[]RecordPanel]{Mode: ChangePreserve},
		HeaderActions:        Change[ActionPlacement]{Mode: ChangePreserve},
		QuickActions:         Change[ActionPlacement]{Mode: ChangePreserve},
		RecordStates:         Change[[]RecordStateRule]{Mode: ChangePreserve},
		PrimaryHeaderActions: Change[[]string]{Mode: ChangePreserve},
	}
}

func validSubmit(operation CommandOperation) SubmitRequest {
	return SubmitRequest{
		CommandID: "command-1", IdempotencyKey: "idempotency-1", BaseCatalogRevision: 41,
		WaitMode: WaitForTerminal, Operation: operation,
	}
}

func validCreateOperation() CommandOperation {
	fields := []string{"Name", "Amount"}
	return CommandOperation{Create: &CreateLayout{
		Document: validDocument(), ListFields: FieldIDListChange{Mode: ChangeSet, Value: &fields},
		ExpectedWorkspaceVersion: pointer("workspace-v1"),
	}}
}

func validReceipts(revision uint64) Receipts {
	return Receipts{
		ProtocolVersion: "1.0", CatalogRevision: revision, SchemaGeneration: 3,
		EngineGeneration: 4, SecurityEpoch: 5, CapabilityVersion: CapabilityName,
	}
}

func validViewRef(revision uint64) CatalogViewRef {
	return CatalogViewRef{CatalogRevision: revision, AuthoringViewDigest: "sha256:" + string(make([]byte, 0)) + "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"}
}

func validWorkspace(revision uint64) Workspace {
	return Workspace{
		ObjectID: "Account", WorkspaceVersion: "workspace-v2", ViewRef: validViewRef(revision), Receipts: validReceipts(revision),
		Layouts: []LayoutSummary{{
			LayoutID: "layout-main", ObjectID: "Account", Name: "Main", Kind: "Detail", IsDefault: true,
			ResourceVersion: "resource-v1",
		}},
		Assignments: []LayoutAssignmentSummary{{
			AssignmentID: "assignment-default", ObjectID: "Account", LayoutID: "layout-main",
			Selectors: AssignmentSelectors{}, Specificity: 0, ResourceVersion: "resource-default",
		}},
	}
}
