package job

import (
	"encoding/json"
	"errors"
	"log"

	"github.com/jobs-scraper/internal/pkg/domain"
	"github.com/jobs-scraper/internal/pkg/infrastructure/rabbitmq"
	"github.com/jobs-scraper/libs/ports"
	"github.com/jobs-scraper/libs/repo"
)

type CreateJob struct {
	jobRepo *repo.JobRepository
	rmq     *rabbitmq.RabbitMQClient
}

func NewCreateJobHandler(jobRepo *repo.JobRepository, rmq *rabbitmq.RabbitMQClient) *CreateJob {
	return &CreateJob{
		jobRepo: jobRepo,
		rmq:     rmq,
	}
}

func (cj *CreateJob) Handle(cmd ports.CreateJobCommand) error {
	jobRequest := domain.SearchQuery{
		Keywords: cmd.Keywords,
		Location: cmd.Location,
		FWT:      cmd.FWT,
		NumPages: cmd.NumPages,
	}

	jsonData, err := json.Marshal(jobRequest)
	if err != nil {
		log.Printf("Error marshaling JSON: %v", err)
		return err
	}

	switch cmd.Provider {
	case domain.LinkedIn:
		if err := cj.rmq.Publish(rabbitmq.LinkedInQueue, rabbitmq.ScraperExchange, jsonData); err != nil {
			log.Printf("Error publishing LinkedIn message: %v", err)
			return err
		}
		log.Printf("Published LinkedIn job request: %s", string(jsonData))
	case domain.Glassdoor:
		if err := cj.rmq.Publish(rabbitmq.GlassDoorQueue, rabbitmq.ScraperExchange, jsonData); err != nil {
			log.Printf("Error publishing Glassdoor message: %v", err)
			return err
		}
		log.Printf("Published Glassdoor job request: %s", string(jsonData))
	default:
		log.Printf("Unsupported job provider: %v", cmd.Provider)
		return errors.New("unsupported job provider")
	}

	return nil
}

// sk-24a0fbede3a8464b85e22360165a3cc9
