package repository

import (
	"context"

	"haixun-backend/internal/library/clock"
	app "haixun-backend/internal/library/errors"
	"haixun-backend/internal/library/errors/code"
	"haixun-backend/internal/model/threads_account/domain/entity"
	domrepo "haixun-backend/internal/model/threads_account/domain/repository"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type secretsMongoRepository struct {
	collection *mongo.Collection
}

func NewSecretsMongoRepository(db *mongo.Database) domrepo.SecretsRepository {
	if db == nil {
		return &secretsMongoRepository{}
	}
	return &secretsMongoRepository{collection: db.Collection(entity.SecretsCollectionName)}
}

func (r *secretsMongoRepository) EnsureIndexes(ctx context.Context) error {
	if r.collection == nil {
		return nil
	}
	_, err := r.collection.Indexes().CreateOne(ctx, mongo.IndexModel{
		Keys: bson.D{{Key: "_id", Value: 1}},
	})
	return err
}

func (r *secretsMongoRepository) FindByAccountID(ctx context.Context, accountID string) (*entity.Secrets, error) {
	if r.collection == nil {
		return nil, app.For(code.ThreadsAccount).DBUnavailable("Mongo is not configured")
	}
	var out entity.Secrets
	err := r.collection.FindOne(ctx, bson.M{"_id": accountID}).Decode(&out)
	if err == mongo.ErrNoDocuments {
		return nil, nil
	}
	if err != nil {
		return nil, err
	}
	return &out, nil
}

func (r *secretsMongoRepository) SaveBrowserStorageState(ctx context.Context, accountID, storageState string) (*entity.Secrets, error) {
	if r.collection == nil {
		return nil, app.For(code.ThreadsAccount).DBUnavailable("Mongo is not configured")
	}
	now := clock.NowUnixNano()
	var out entity.Secrets
	err := r.collection.FindOneAndUpdate(
		ctx,
		bson.M{"_id": accountID},
		bson.M{
			"$set": bson.M{
				"browser_storage_state": storageState,
				"update_at":             now,
			},
			"$setOnInsert": bson.M{"_id": accountID},
		},
		options.FindOneAndUpdate().SetUpsert(true).SetReturnDocument(options.After),
	).Decode(&out)
	if err != nil {
		return nil, err
	}
	return &out, nil
}
