package domain

import "context"

type Repository interface {
	Insert(ctx context.Context, j *Job) error
	// InsertUniqueRef atomically inserts j unless a job with the same
	// owner+template+ref already exists, in which case the existing job is
	// returned with created=false. Check-then-insert is not enough: concurrent
	// schedulers would each see "no existing job" and all insert.
	InsertUniqueRef(ctx context.Context, j *Job) (stored *Job, created bool, err error)
	Update(ctx context.Context, j *Job) error
	// UpdateOwned atomically requires the current running lease to belong to leaseOwner.
	UpdateOwned(ctx context.Context, j *Job, leaseOwner string) error
	RenewLease(ctx context.Context, id, leaseOwner string, leaseExpiresAt int64) error
	FindByID(ctx context.Context, id string) (*Job, error)
	ListByOwner(ctx context.Context, ownerUID int64) ([]*Job, error)
	// ListByOwnerTab 分頁＋分桶；total 為該 tab 總筆數
	ListByOwnerTab(ctx context.Context, ownerUID int64, tab string, page, pageSize int) (list []*Job, total int64, err error)
	// ClaimNext atomically claims a due queued job or a running job with an expired lease.
	ClaimNext(ctx context.Context, workerID string) (*Job, error)
	// CancelPendingByRef cancels pending/queued jobs of template+ref (e.g. reschedule renew).
	CancelPendingByRef(ctx context.Context, ownerUID int64, template, refID string) error
	// CountActiveByOwnerAndTemplate counts an owner's non-terminal (pending/
	// queued/running) jobs of the given template — used to cap concurrent
	// CPU-heavy jobs (e.g. Threads profile scrape) per member.
	CountActiveByOwnerAndTemplate(ctx context.Context, ownerUID int64, template string) (int64, error)
	// Delete hard-removes a job by id.
	Delete(ctx context.Context, id string) error
	// DeleteTerminalBefore removes terminal jobs whose completion time is before beforeNs.
	// Returns number of deleted documents.
	DeleteTerminalBefore(ctx context.Context, beforeNs int64) (int64, error)
}
