package server

import (
	"context"
	"sync"

	"github.com/go-nunu/nunu-layout-advanced/internal/job"
	"github.com/go-nunu/nunu-layout-advanced/pkg/log"
	"go.uber.org/zap"
)

type JobServer struct {
	log          *log.Logger
	userJob      job.UserJob
	whitelistJob job.WhitelistJob
	wg           sync.WaitGroup
	wafLogJob    job.WafLogJob
}

func NewJobServer(
	log *log.Logger,
	userJob job.UserJob,
	whitelistJob job.WhitelistJob,
	wafLogJob job.WafLogJob,
) *JobServer {
	return &JobServer{
		log:          log,
		userJob:      userJob,
		whitelistJob: whitelistJob,
		wafLogJob:    wafLogJob,
	}
}

func (j *JobServer) Start(ctx context.Context) error {
	j.log.Info("job server starting...")

	// 启动 UserJob 的消费者
	//j.wg.Add(1)
	//go func() {
	//	defer j.wg.Done()
	//	j.userJob.RegisterConsumer(ctx)
	//}()

	// 启动 WhitelistJob 的消费者
	j.wg.Add(1)
	go func() {
		defer func() {
			if r := recover(); r != nil {
				j.log.Error("whitelistJob domain consumer panic", zap.Any("error", r))
			}
			j.wg.Done()
		}()
		j.whitelistJob.DomainConsumer(ctx)
	}()
	j.wg.Add(1)
	go func() {
		defer func() {
			if r := recover(); r != nil {
				j.log.Error("whitelistJob ip consumer panic", zap.Any("error", r))
			}
			j.wg.Done()
		}()
		j.whitelistJob.IpConsumer(ctx)
	}()

	j.wg.Add(1)
	go func() {
		defer func() {
			if r := recover(); r != nil {
				j.log.Error("wafLogJob domain consumer panic", zap.Any("error", r))
			}
			j.wg.Done()
		}()
		j.wafLogJob.AddWafLogConsumer(ctx)
	}()

	j.wg.Wait()

	return nil
}
func (j *JobServer) Stop(ctx context.Context) error {
	return nil
}
