package docs

import (
	"context"
	"encoding/json"
	"time"

	"github.com/google/uuid"

	"github.com/yan1h/agent-coding-workflow/internal/infra/errs"
	"github.com/yan1h/agent-coding-workflow/internal/jobs"
)

// Enqueuer is the subset of jobs.Repository the service needs.
type Enqueuer interface {
	Enqueue(ctx context.Context, typ jobs.JobType, payload json.RawMessage, scheduledAt time.Time, maxAttempts int32) (*jobs.Job, error)
}

// Service is the docs application service.
type Service interface {
	// EnqueueCommitSummary enqueues a docs.commit_summary job for the given
	// commit. Idempotent at the data layer via UNIQUE(workspace, commit, kind).
	EnqueueCommitSummary(ctx context.Context, wsID uuid.UUID, worktreeID *uuid.UUID, branch, commitSHA string) error
}

type service struct {
	jobs    Enqueuer
	enabled bool
}

// NewService constructs the docs Service. When enabled is false, EnqueueCommitSummary
// is a no-op so the commit path stays free of doc-gen overhead.
func NewService(jobsRepo Enqueuer, enabled bool) Service {
	return &service{jobs: jobsRepo, enabled: enabled}
}

func (s *service) EnqueueCommitSummary(ctx context.Context, wsID uuid.UUID, worktreeID *uuid.UUID, branch, commitSHA string) error {
	if !s.enabled {
		return nil
	}
	if commitSHA == "" {
		return errs.New(errs.CodeInvalidInput, "commit_sha required")
	}
	payload, _ := json.Marshal(summaryPayload{
		WorkspaceID: wsID,
		WorktreeID:  worktreeID,
		Branch:      branch,
		CommitSHA:   commitSHA,
	})
	if _, err := s.jobs.Enqueue(ctx, JobTypeCommitSummary, payload, time.Now(), 3); err != nil {
		return errs.Wrap(err, errs.CodeInternal, "enqueue docs.commit_summary")
	}
	return nil
}
