// Package port defines interface contracts for external adapters.
package port

import (
	"context"
	"time"

	"github.com/orchard9/rdev/internal/domain"
)

// OperationRepository manages operation records for debugging and observability.
// Operations are tracked with steps, enabling developers to pinpoint failures
// without digging through logs.
type OperationRepository interface {
	// Create creates a new operation record.
	Create(ctx context.Context, op *domain.Operation) error

	// Update updates an existing operation record.
	Update(ctx context.Context, op *domain.Operation) error

	// Get retrieves an operation by ID.
	// Returns ErrOperationNotFound if the operation does not exist.
	Get(ctx context.Context, id string) (*domain.Operation, error)

	// GetByCommitSHA finds the operation that created a specific commit.
	// Used to link builds to the operation that triggered them.
	// Returns ErrOperationNotFound if no operation matches.
	GetByCommitSHA(ctx context.Context, projectID, sha string) (*domain.Operation, error)

	// List returns operations matching the filter criteria.
	List(ctx context.Context, filter domain.OperationFilters) ([]*domain.Operation, error)

	// AddStep appends a new step to an operation.
	AddStep(ctx context.Context, operationID string, step domain.OperationStep) error

	// UpdateStep updates an existing step within an operation.
	// The step is identified by name.
	UpdateStep(ctx context.Context, operationID string, step domain.OperationStep) error

	// Complete marks an operation as completed or failed.
	// Sets completed_at, duration_ms, and optionally output/error fields.
	Complete(ctx context.Context, operationID string, status domain.OperationStatus, output map[string]any, errMsg, errDetail string) error

	// SetCommitSHA updates the commit_sha field for an operation.
	// Called after a git commit is created as part of the operation.
	SetCommitSHA(ctx context.Context, operationID, sha string) error

	// SetTriggeredBy sets the triggered_by field to link to a parent operation.
	SetTriggeredBy(ctx context.Context, operationID, parentID string) error

	// DeleteOlderThan removes operations older than the specified time.
	// Returns the number of deleted records.
	// Used by the cleanup worker for 30-day retention.
	DeleteOlderThan(ctx context.Context, cutoff time.Time) (int64, error)
}
