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 ExpenseNonstockRepository interface {
	repository.BaseRepository[entity.ExpenseNonstock]
	IdExists(ctx context.Context, id uint64) (bool, error)
	GetByExpenseID(ctx context.Context, expenseID uint64, id uint64) (bool, error)
	GetWithRelations(ctx context.Context, id uint64) (*entity.ExpenseNonstock, error)
}

type ExpenseNonstockRepositoryImpl struct {
	*repository.BaseRepositoryImpl[entity.ExpenseNonstock]
}

func NewExpenseNonstockRepository(db *gorm.DB) ExpenseNonstockRepository {
	return &ExpenseNonstockRepositoryImpl{
		BaseRepositoryImpl: repository.NewBaseRepository[entity.ExpenseNonstock](db),
	}
}

func (r *ExpenseNonstockRepositoryImpl) IdExists(ctx context.Context, id uint64) (bool, error) {
	return repository.Exists[entity.ExpenseNonstock](ctx, r.DB(), uint(id))
}

func (r *ExpenseNonstockRepositoryImpl) GetByExpenseID(ctx context.Context, expenseID uint64, id uint64) (bool, error) {
	var count int64
	err := r.DB().WithContext(ctx).Model(&entity.ExpenseNonstock{}).
		Where("id = ? AND expense_id = ?", id, expenseID).
		Count(&count).Error
	if err != nil {
		return false, err
	}
	return count > 0, nil
}

func (r *ExpenseNonstockRepositoryImpl) GetWithRelations(ctx context.Context, id uint64) (*entity.ExpenseNonstock, error) {
	var expenseNonstock entity.ExpenseNonstock
	err := r.DB().WithContext(ctx).
		Where("id = ?", id).
		Preload("Nonstock", func(db *gorm.DB) *gorm.DB {
			return db.Preload("Suppliers")
		}).
		First(&expenseNonstock).Error
	if err != nil {
		return nil, err
	}
	return &expenseNonstock, nil
}
