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 StockLogRepository interface {
	repository.BaseRepository[entity.StockLog]
	GetByFlaggable(ctx context.Context, logType string, logId uint) ([]*entity.StockLog, error)
	GetByProductWarehouse(ctx context.Context, productWarehouseId uint, limit int) ([]*entity.StockLog, error)
	GetByTransactionType(ctx context.Context, transactionType string, limit int) ([]*entity.StockLog, error)
	ApplyProductWarehouseFilters(db *gorm.DB, productID, warehouseID uint) *gorm.DB
}

type StockLogRepositoryImpl struct {
	*repository.BaseRepositoryImpl[entity.StockLog]
}

func NewStockLogRepository(db *gorm.DB) StockLogRepository {
	return &StockLogRepositoryImpl{
		BaseRepositoryImpl: repository.NewBaseRepository[entity.StockLog](db),
	}
}

func (r *StockLogRepositoryImpl) GetByFlaggable(ctx context.Context, logType string, logId uint) ([]*entity.StockLog, error) {
	var stockLogs []*entity.StockLog

	err := r.DB().WithContext(ctx).
		Where("loggable_type = ? AND log_id = ?", logType, logId).
		Preload("ProductWarehouse").
		Preload("ProductWarehouse.Product").
		Preload("ProductWarehouse.Warehouse").
		Order("created_at DESC").
		Find(&stockLogs).Error

	if err != nil {
		return nil, err
	}

	return stockLogs, nil
}

func (r *StockLogRepositoryImpl) GetByProductWarehouse(ctx context.Context, productWarehouseId uint, limit int) ([]*entity.StockLog, error) {
	var stockLogs []*entity.StockLog

	query := r.DB().WithContext(ctx).
		Where("product_warehouse_id = ?", productWarehouseId).
		Preload("ProductWarehouse").
		Preload("ProductWarehouse.Product").
		Preload("ProductWarehouse.Warehouse").
		Order("created_at DESC")

	if limit > 0 {
		query = query.Limit(limit)
	}

	err := query.Find(&stockLogs).Error
	if err != nil {
		return nil, err
	}

	return stockLogs, nil
}

func (r *StockLogRepositoryImpl) GetByTransactionType(ctx context.Context, transactionType string, limit int) ([]*entity.StockLog, error) {
	var stockLogs []*entity.StockLog

	query := r.DB().WithContext(ctx).
		Where("transaction_type = ?", transactionType).
		Preload("ProductWarehouse").
		Preload("ProductWarehouse.Product").
		Preload("ProductWarehouse.Warehouse").
		Order("created_at DESC")

	if limit > 0 {
		query = query.Limit(limit)
	}

	err := query.Find(&stockLogs).Error
	if err != nil {
		return nil, err
	}

	return stockLogs, nil
}

func (r *StockLogRepositoryImpl) ApplyProductWarehouseFilters(db *gorm.DB, productID, warehouseID uint) *gorm.DB {
	if productID == 0 && warehouseID == 0 {
		return db
	}

	db = db.Joins("JOIN product_warehouses ON product_warehouses.id = stock_logs.product_warehouse_id")

	if productID > 0 {
		db = db.Where("product_warehouses.product_id = ?", productID)
	}
	if warehouseID > 0 {
		db = db.Where("product_warehouses.warehouse_id = ?", warehouseID)
	}

	return db
}
