package usecase

import (
	"context"
	"fmt"

	notifconfig "gateway/internal/model/notification/config"
	"gateway/internal/model/notification/domain/enum"
	domtpl "gateway/internal/model/notification/domain/template"
	domusecase "gateway/internal/model/notification/domain/usecase"
	"gateway/internal/model/notification/provider/email"
	"gateway/internal/model/notification/provider/sms"
)

type deliveryDeps struct {
	Renderer domtpl.Renderer
	Email    *email.Chain
	SMS      *sms.Chain
	Config   notifconfig.Config
}

func (d deliveryDeps) deliver(ctx context.Context, req *domusecase.SendRequest, rendered *domtpl.Rendered) (provider, messageID string, err error) {
	switch req.Channel {
	case enum.ChannelEmail:
		if d.Email == nil {
			return "", "", errb.SysNotImplemented("email provider chain is not configured")
		}
		return d.Email.Send(ctx, &email.Message{
			From:    d.Config.Email.From,
			To:      []string{req.Target},
			Subject: rendered.Subject,
			Body:    rendered.Body,
		})
	case enum.ChannelSMS:
		if d.SMS == nil {
			return "", "", errb.SysNotImplemented("sms provider chain is not configured")
		}
		name := req.UID
		if name == "" {
			name = "User"
		}
		return d.SMS.Send(ctx, &sms.Message{
			PhoneNumber:   req.Target,
			RecipientName: name,
			Body:          rendered.SMSText,
		})
	default:
		return "", "", errb.SysNotImplemented(fmt.Sprintf("channel %q delivery not implemented", req.Channel))
	}
}

func sendRequestFromJob(job *domusecase.RetryJob) *domusecase.SendRequest {
	return &domusecase.SendRequest{
		TenantID:         job.TenantID,
		UID:              job.UID,
		Channel:          job.Channel,
		Kind:             job.Kind,
		Target:           job.Target,
		Locale:           job.Locale,
		Data:             job.Data,
		DoNotPersistBody: job.DoNotPersistBody,
	}
}
