package repository

import (
	"context"

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

type InitialRepository interface {
	repository.BaseRepository[entity.Payment]
	BankExists(ctx context.Context, bankId uint) (bool, error)
	CustomerExists(ctx context.Context, customerId uint) (bool, error)
	SupplierExists(ctx context.Context, supplierId uint) (bool, error)
	NextPaymentSequence(ctx context.Context) (int64, error)
}

type InitialRepositoryImpl struct {
	*repository.BaseRepositoryImpl[entity.Payment]
	db *gorm.DB
}

func NewInitialRepository(db *gorm.DB) InitialRepository {
	return &InitialRepositoryImpl{
		BaseRepositoryImpl: repository.NewBaseRepository[entity.Payment](db),
		db:                 db,
	}
}

func (r *InitialRepositoryImpl) BankExists(ctx context.Context, bankId uint) (bool, error) {
	return repository.Exists[entity.Bank](ctx, r.db, bankId)
}

func (r *InitialRepositoryImpl) CustomerExists(ctx context.Context, customerId uint) (bool, error) {
	return repository.Exists[entity.Customer](ctx, r.db, customerId)
}

func (r *InitialRepositoryImpl) SupplierExists(ctx context.Context, supplierId uint) (bool, error) {
	return repository.Exists[entity.Supplier](ctx, r.db, supplierId)
}

func (r *InitialRepositoryImpl) NextPaymentSequence(ctx context.Context) (int64, error) {
	var next int64
	if err := r.db.WithContext(ctx).
		Raw("SELECT nextval('payments_code_seq')").
		Scan(&next).Error; err != nil {
		return 0, err
	}
	return next, nil
}
