package repositories

import (
	"context"
	"fmt"

	"gitlab.com/mbugroup/lti-api.git/internal/common/repository"
	entity "gitlab.com/mbugroup/lti-api.git/internal/entities"
	"gorm.io/gorm"
)

type StockTransferRepository interface {
	repository.BaseRepository[entity.StockTransfer]
	// get sequence for movement number
	GetNextMovementNumber(ctx context.Context) (int64, error)
	GenerateMovementNumber(ctx context.Context) (string, error)
}

type StockTransferRepositoryImpl struct {
	*repository.BaseRepositoryImpl[entity.StockTransfer]
}

func NewStockTransferRepository(db *gorm.DB) StockTransferRepository {
	return &StockTransferRepositoryImpl{
		BaseRepositoryImpl: repository.NewBaseRepository[entity.StockTransfer](db),
	}
}

func (r *StockTransferRepositoryImpl) GetNextMovementNumber(ctx context.Context) (int64, error) {
	var seq int64
	err := r.DB().WithContext(ctx).Raw("SELECT nextval('stock_transfer_seq')").Scan(&seq).Error
	if err != nil {
		return 0, err
	}
	return seq, nil
}

func (r *StockTransferRepositoryImpl) GenerateMovementNumber(ctx context.Context) (string, error) {
	seq, err := r.GetNextMovementNumber(ctx)
	if err != nil {
		return "", err
	}
	movementNumber := fmt.Sprintf("PND-LTI-%05d", seq)
	return movementNumber, nil
}
