package job

import (
	"encoding/json"
	"log"

	"github.com/jobs-scraper/infrastructure/rabbitmq"
	"github.com/jobs-scraper/internal/domain"
	"github.com/jobs-scraper/internal/ports"
	"github.com/jobs-scraper/internal/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
	} else {
		if err := cj.rmq.Publish(rabbitmq.LinkedInQueue, rabbitmq.ScraperExchange, jsonData); err != nil {
			log.Printf("Error publishing message: %v", err)

			return err
		} else {
			log.Printf("Published job request: %s", string(jsonData))
		}
	}

	return nil
}

// sk-24a0fbede3a8464b85e22360165a3cc9
