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 PaymentRepository 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)
	SupplierCategory(ctx context.Context, supplierId uint) (string, error)
	NextPaymentSequence(ctx context.Context) (int64, error)
}

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

func NewPaymentRepository(db *gorm.DB) PaymentRepository {
	return &PaymentRepositoryImpl{
		BaseRepositoryImpl: repository.NewBaseRepository[entity.Payment](db),
		db:                 db,
	}
}

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

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

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

func (r *PaymentRepositoryImpl) SupplierCategory(ctx context.Context, supplierId uint) (string, error) {
	var supplier entity.Supplier
	if err := r.db.WithContext(ctx).
		Select("id", "category").
		First(&supplier, supplierId).Error; err != nil {
		return "", err
	}
	return supplier.Category, nil
}

func (r *PaymentRepositoryImpl) 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
}
