package models

import (
	"context"
	"time"

	"gitea.hostxtra.co.uk/mrhid6/vantage/admin/internal/db"
	"go.mongodb.org/mongo-driver/v2/bson"
	"go.mongodb.org/mongo-driver/v2/mongo"
)

// ClaimEvent records an event ID before it is processed and reports whether THIS
// call is the one that claimed it.
//
// The unique index on event_id turns a duplicate insert into a duplicate-key
// error, which is the signal that another delivery of the same event already
// owns it — so this returns (false, nil) and the caller answers 200 without
// acting. A genuine error returns (false, err).
func ClaimEvent(ctx context.Context, eventID, eventType string) (bool, error) {
	_, err := db.Admin("paddle_events").InsertOne(ctx, PaddleEvent{
		EventID:    eventID,
		EventType:  eventType,
		ReceivedAt: time.Now().UTC(),
	})
	if err == nil {
		return true, nil
	}
	if mongo.IsDuplicateKeyError(err) {
		return false, nil
	}
	return false, err
}

// MarkEventProcessed stamps success, or records the error for staff visibility.
// A failed event keeps no processed_at, so a retry re-runs it.
func MarkEventProcessed(ctx context.Context, eventID string, procErr error) error {
	set := bson.M{}
	if procErr != nil {
		set["error"] = procErr.Error()
	} else {
		now := time.Now().UTC()
		set["processed_at"] = now
		set["error"] = ""
	}
	_, err := db.Admin("paddle_events").UpdateOne(ctx,
		bson.M{"event_id": eventID}, bson.M{"$set": set})
	return err
}
