package marketing

import (
	"fmt"

	"github.com/go-playground/validator/v10"
	"github.com/gofiber/fiber/v2"
	"gorm.io/gorm"

	commonRepo "gitlab.com/mbugroup/lti-api.git/internal/common/repository"
	commonSvc "gitlab.com/mbugroup/lti-api.git/internal/common/service"
	rProductWarehouse "gitlab.com/mbugroup/lti-api.git/internal/modules/inventory/product-warehouses/repositories"
	repository "gitlab.com/mbugroup/lti-api.git/internal/modules/marketing/repositories"
	service "gitlab.com/mbugroup/lti-api.git/internal/modules/marketing/services"
	rCustomer "gitlab.com/mbugroup/lti-api.git/internal/modules/master/customers/repositories"
	rWarehouse "gitlab.com/mbugroup/lti-api.git/internal/modules/master/warehouses/repositories"
	rProjectFlockKandang "gitlab.com/mbugroup/lti-api.git/internal/modules/production/project_flocks/repositories"
	rShared "gitlab.com/mbugroup/lti-api.git/internal/modules/shared/repositories"
	rUser "gitlab.com/mbugroup/lti-api.git/internal/modules/users/repositories"
	sUser "gitlab.com/mbugroup/lti-api.git/internal/modules/users/services"
	"gitlab.com/mbugroup/lti-api.git/internal/utils"
)

type MarketingModule struct{}

func (MarketingModule) RegisterRoutes(router fiber.Router, db *gorm.DB, validate *validator.Validate) {
	// Initialize repositories
	marketingRepo := repository.NewMarketingRepository(db)
	marketingProductRepo := repository.NewMarketingProductRepository(db)
	marketingDeliveryProductRepo := repository.NewMarketingDeliveryProductRepository(db)
	userRepo := rUser.NewUserRepository(db)
	customerRepo := rCustomer.NewCustomerRepository(db)
	productWarehouseRepo := rProductWarehouse.NewProductWarehouseRepository(db)
	projectFlockPopulationRepo := rProjectFlockKandang.NewProjectFlockPopulationRepository(db)
	stockLogRepo := rShared.NewStockLogRepository(db)

	fifoStockV2Service := commonSvc.NewFifoStockV2Service(db, utils.Log)

	approvalRepo := commonRepo.NewApprovalRepository(db)
	approvalSvc := commonSvc.NewApprovalService(approvalRepo)

	if err := approvalSvc.RegisterWorkflowSteps(utils.ApprovalWorkflowMarketing, utils.MarketingApprovalSteps); err != nil {
		panic(fmt.Sprintf("failed to register marketing approval workflow: %v", err))
	}

	warehouseRepo := rWarehouse.NewWarehouseRepository(db)
	projectFlockKandangRepo := rProjectFlockKandang.NewProjectFlockKandangRepository(db)

	salesOrdersService := service.NewSalesOrdersService(marketingRepo, customerRepo, productWarehouseRepo, userRepo, approvalSvc, fifoStockV2Service, warehouseRepo, projectFlockKandangRepo, validate)
	deliveryOrdersService := service.NewDeliveryOrdersService(marketingRepo, marketingProductRepo, marketingDeliveryProductRepo, stockLogRepo, productWarehouseRepo, projectFlockPopulationRepo, approvalSvc, fifoStockV2Service, validate)
	userService := sUser.NewUserService(userRepo, validate)

	RegisterRoutes(router, userService, salesOrdersService, deliveryOrdersService)
}
