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 ProductWarehouseRepository interface {
	repository.BaseRepository[entity.ProductWarehouse]
	ProductWarehouseExists(ctx context.Context, productId, warehouseId uint, excludeID *uint) (bool, error)
	IsProductExist(ctx context.Context, productId uint) (bool, error)
	IsWarehouseExist(ctx context.Context, warehouseId uint) (bool, error)
	ProductWarehouseExistByProductAndWarehouseID(ctx context.Context, productId, warehouseId uint) (bool, error)
	ExistsByID(ctx context.Context, id uint) (bool, error)
	GetProductWarehouseByProductAndWarehouseID(ctx context.Context, productId, warehouseId uint) (*entity.ProductWarehouse, error)
}

type ProductWarehouseRepositoryImpl struct {
	*repository.BaseRepositoryImpl[entity.ProductWarehouse]
	db *gorm.DB
}

func NewProductWarehouseRepository(db *gorm.DB) ProductWarehouseRepository {
	return &ProductWarehouseRepositoryImpl{
		BaseRepositoryImpl: repository.NewBaseRepository[entity.ProductWarehouse](db),
		db:                 db,
	}
}

func (r *ProductWarehouseRepositoryImpl) ProductWarehouseExists(ctx context.Context, productId, warehouseId uint, excludeID *uint) (bool, error) {
	var count int64
	query := r.db.WithContext(ctx).Model(&entity.ProductWarehouse{}).
		Where("product_id = ? AND warehouse_id = ?", productId, warehouseId)
	if excludeID != nil {
		query = query.Where("id != ?", *excludeID)
	}
	if err := query.Count(&count).Error; err != nil {
		return false, err
	}
	return count > 0, nil
}

func (r *ProductWarehouseRepositoryImpl) IsProductExist(ctx context.Context, productId uint) (bool, error) {
	return repository.Exists[entity.Product](ctx, r.db, productId)
}
func (r *ProductWarehouseRepositoryImpl) IsWarehouseExist(ctx context.Context, warehouseId uint) (bool, error) {
	return repository.Exists[entity.Warehouse](ctx, r.db, warehouseId)
}

func (r *ProductWarehouseRepositoryImpl) ExistsByID(ctx context.Context, id uint) (bool, error) {
	return repository.Exists[entity.ProductWarehouse](ctx, r.db, id)
}

func (r *ProductWarehouseRepositoryImpl) ProductWarehouseExistByProductAndWarehouseID(ctx context.Context, productId, warehouseId uint) (bool, error) {
	var count int64
	if err := r.db.WithContext(ctx).
		Model(&entity.ProductWarehouse{}).
		Where("product_id = ? AND warehouse_id = ?", productId, warehouseId).
		Count(&count).Error; err != nil {
		return false, err
	}
	return count > 0, nil
}

func (r *ProductWarehouseRepositoryImpl) GetProductWarehouseByProductAndWarehouseID(ctx context.Context, productId, warehouseId uint) (*entity.ProductWarehouse, error) {
	var productWarehouse entity.ProductWarehouse
	if err := r.DB().WithContext(ctx).Where("product_id = ? AND warehouse_id = ?", productId, warehouseId).First(&productWarehouse).Error; err != nil {
		return nil, err
	}
	return &productWarehouse, nil
}
