package customer

import (
	"context"
	"log"
	"time"

	arango_db "git.slaventius.ru/test3k/authDB/internal/transport/arango"
	"git.slaventius.ru/test3k/umate/pkg/kafka"

	"github.com/arangodb/go-driver"
)

type CustomerRepository struct {
	ctx        context.Context
	database   driver.Database
	collection driver.Collection
	Customers  map[string]Customer
}

// Хранилище покупателей
func NewCustomerRepository(ctx context.Context, database *arango_db.DataBase) *CustomerRepository {
	collName := "customers"
	collection, err := database.AddCollection(collName)
	if err != nil {
		log.Fatal(err)
	}

	return &CustomerRepository{
		ctx:        ctx,
		database:   database.DB,
		collection: collection,
		Customers:  make(map[string]Customer),
	}
}

// Новый покупатель
func (r *CustomerRepository) NewCustomer(login string, password string, email string) Customer {
	return Customer{
		SimpleRow:          *NewSimpleRow(r.ctx, r.database, r.collection),
		Login:              login,
		Password:           password,
		TimeReregistration: time.Now(),
		MessageRegistration: kafka.MessageRegistration{
			Email: email,
			Code:  time.Now().Format(StampTemplate),
		},
	}
}

func (r *CustomerRepository) FetchAll() error {
	params := make(map[string]interface{})
	params["@coll"] = r.collection.Name()

	//
	query := "for el in @@coll return el"
	cursor, err := r.database.Query(r.ctx, query, params)
	if err != nil {
		return err
	}
	defer cursor.Close()

	//
	for {
		rec := Customer{}
		meta, era := cursor.ReadDocument(r.ctx, &rec)
		if driver.IsNoMoreDocuments(era) {
			break
		}

		//
		rec.ctx = r.ctx
		rec.collection = r.collection
		rec.database = r.database
		rec.key = meta.Key

		r.Customers[rec.Login] = rec
	}

	return nil
}