package background

import (
	"context"
	"fmt"
	"strconv"
	"time"

	"github.com/rs/zerolog/log"
	"source.gleipnir.technology/Gleipnir/nidus-sync/db"
	"source.gleipnir.technology/Gleipnir/nidus-sync/db/gen/nidus-sync/public/model"
	query "source.gleipnir.technology/Gleipnir/nidus-sync/db/query/public"
)

func NewAudioTranscode(ctx context.Context, txn db.Ex, audio_id int32) error {
	return newJob(ctx, txn, model.Jobtype_AudioTranscode, audio_id)
}
func NewComplianceMailer(ctx context.Context, txn db.Ex, compliance_report_request_id int32) error {
	return newJob(ctx, txn, model.Jobtype_ComplianceMailerSend, compliance_report_request_id)
}
func NewCSVCommit(ctx context.Context, txn db.Ex, csv_id int32) error {
	return newJob(ctx, txn, model.Jobtype_CsvCommit, csv_id)
}
func NewCSVImport(ctx context.Context, txn db.Ex, csv_id int32) error {
	return newJob(ctx, txn, model.Jobtype_CsvImport, csv_id)
}
func NewEmailSend(ctx context.Context, txn db.Ex, email_id int32) error {
	return newJob(ctx, txn, model.Jobtype_EmailSend, email_id)
}
func NewLabelStudioAudioCreate(ctx context.Context, txn db.Ex, note_audio_id int32) error {
	return newJob(ctx, txn, model.Jobtype_LabelStudioAudioCreate, note_audio_id)
}
func NewTextRespond(ctx context.Context, txn db.Ex, text_id int32) error {
	return newJob(ctx, txn, model.Jobtype_TextRespond, text_id)
}
func NewTextSend(ctx context.Context, txn db.Ex, job_id int32) error {
	return newJob(ctx, txn, model.Jobtype_TextSend, job_id)
}
func newJob(ctx context.Context, txn db.Ex, t model.Jobtype, id int32) error {
	job := model.Job{
		Created: time.Now(),
		Type:    t,
		RowID:   id,
	}
	j, err := query.JobInsert(ctx, txn, job)
	if err != nil {
		return fmt.Errorf("insert job: %w", err)
	}
	err = query.JobNotify(ctx, txn, "new_job", strconv.Itoa(int(j.ID)))
	if err != nil {
		return fmt.Errorf("notify job: %w", err)
	}
	log.Debug().Int32("id", j.ID).Int32("row_id", id).Msg("created job, added notify")
	return nil
}
