package pulls

import (
	"net/http"
	"time"

	comatproto "github.com/bluesky-social/indigo/api/atproto"
	"github.com/bluesky-social/indigo/atproto/syntax"
	lexutil "github.com/bluesky-social/indigo/lex/util"

	"tangled.org/core/api/tangled"
	"tangled.org/core/appview/models"
	"tangled.org/core/tid"
)

func (s *Pulls) writePullStatusRecord(r *http.Request, actorDid string, subject syntax.ATURI, value models.StateValue) error {
	client, err := s.oauth.AuthorizedClient(r)
	if err != nil {
		return err
	}

	record, err := models.AsPullStatusRecord(subject, value, time.Now())
	if err != nil {
		return err
	}

	_, err = comatproto.RepoPutRecord(r.Context(), client, &comatproto.RepoPutRecord_Input{
		Collection: tangled.RepoPullStatusNSID,
		Repo:       actorDid,
		Rkey:       tid.TID(),
		Record: &lexutil.LexiconTypeDecoder{
			Val: &record,
		},
	})
	return err
}
