package automation

import (
	"context"
	"database/sql"
	"encoding/base64"
	"encoding/json"
	"strings"
)

// Historical attempts remain readable and must fence identity recovery. Seed
// their persisted format directly: no running service produces these rows now.
type legacyConnectorAttemptFixture struct {
	AttemptID, LinkKey string
	AttemptOrdinal     int
	Identity           ConnectorPushDurableIdentity
	Snapshot           ConnectorPushDurableSnapshot
}

func seedLegacyConnectorAttempt(ctx context.Context, db *sql.DB, fixture legacyConnectorAttemptFixture) (*ConnectorPushAttempt, error) {
	identity, snapshot := fixture.Identity, fixture.Snapshot
	linkKey, err := identity.LinkKey()
	if err != nil {
		return nil, err
	}
	snapshot.ProfileContractHash = ConnectorPushProfileContractHash(snapshot)
	encode := func(v any) string {
		b, err := json.Marshal(v)
		if err != nil {
			panic(err)
		}
		return string(b)
	}
	columns := []string{"Id", "LinkKey", "AttemptOccupancyKey", "Status", "DispatchLane", "AttemptOrdinal",
		"ConnectorOwnerKey", "ActionSlotId", "ActionType", "SourceObject", "SourceRecordId", "DestinationSlotId",
		"RequesterOwnerPack", "ProfileOwnerPack", "ConnectorNamespace", "FlowDeveloperName", "FlowActionName", "TargetObject", "ProfileName", "CreatedPackInstallId",
		"CredentialRef", "EndpointClass", "RetryPolicy", "ProfileContractHash", "CreatePathTemplate", "UpdatePathTemplate", "ResponseIdPath", "RemoteIdField", "RemoteIdProvenanceField",
		"MappingFingerprint", "BodyFingerprint", "OriginatingUserId", "OriginatingUserSessionJSON", "AllowedSourceFieldsJSON", "AssociationSourceRecordIdsJSON",
		"RequestIdempotencyKey", "RequestMethod", "RequestRelativePath", "RequestHeaders", "RequestBodyBase64", "RequestBodyHash"}
	args := []any{fixture.AttemptID, linkKey, linkKey, ConnectorPushAttemptStatusPending, ConnectorPushAttemptDispatchLaneConfigured, fixture.AttemptOrdinal,
		identity.ConnectorOwnerKey, identity.ActionSlotID, identity.ActionType, identity.SourceObject, identity.SourceRecordID, identity.DestinationSlotID,
		snapshot.RequesterOwnerPack, snapshot.ProfileOwnerPack, snapshot.ConnectorNamespace, snapshot.FlowDeveloperName, snapshot.FlowActionName, snapshot.TargetObject, snapshot.ProfileName, snapshot.CreatedPackInstallID,
		snapshot.CredentialRef, snapshot.EndpointClass, encode(snapshot.RetryPolicy), snapshot.ProfileContractHash, snapshot.CreatePathTemplate, snapshot.UpdatePathTemplate, snapshot.ResponseIDPath, snapshot.RemoteIDField, snapshot.RemoteIDProvenanceField,
		snapshot.MappingFingerprint, snapshot.BodyFingerprint, snapshot.OriginatingUserID, encode(snapshot.OriginatingUserSession), encode(snapshot.AllowedSourceFields), encode(snapshot.AssociationSourceRecordIDs),
		snapshot.RequestIdempotencyKey, snapshot.RequestMethod, snapshot.RequestRelativePath, encode(snapshot.RequestHeaders), base64.StdEncoding.EncodeToString(snapshot.RequestBody), snapshot.RequestBodyHash}
	_, err = db.ExecContext(ctx, "INSERT INTO _System_ConnectorPushAttempt ("+strings.Join(columns, ",")+") VALUES ("+strings.TrimSuffix(strings.Repeat("?,", len(args)), ",")+")", args...)
	if err != nil {
		return nil, err
	}
	return &ConnectorPushAttempt{ID: fixture.AttemptID, LinkKey: linkKey, Identity: identity, Snapshot: snapshot}, nil
}
