package automationcutover

import (
	"context"
	"fmt"
	"time"

	automationstore "github.com/tidbcloud/AgentTeam/internal/store/automation"
	contentstorestore "github.com/tidbcloud/AgentTeam/internal/store/content"
	"gorm.io/gorm"
)

// Store owns the narrow cross-domain transaction that makes an Automation
// projection visible only while the caller still owns the exact legacy
// authority fence. It does not coordinate or wait for AGS writers.
type Store struct{ db *gorm.DB }

func New(db *gorm.DB) *Store { return &Store{db: db} }

func (store *Store) RecordLegacyContentPublication(
	ctx context.Context,
	publication automationstore.AutomationContentPublication,
	definitions []automationstore.AutomationContentDefinition,
	expectedCurrentVersionID string,
	mode automationstore.ContentPublicationRecordMode,
	fence contentstorestore.LegacyAuthorityFence,
	now time.Time,
) error {
	if store == nil || store.db == nil {
		return fmt.Errorf("automation cutover store is not configured")
	}
	return store.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
		if err := contentstorestore.New(tx).RequireLegacyAuthorityFence(ctx, fence, now); err != nil {
			return err
		}
		return automationstore.New(tx).RecordContentPublication(ctx, publication, definitions, expectedCurrentVersionID, mode)
	})
}
