package recipientimp

import (
	"context"

	"github.com/tech/sendico/pkg/db/recipient"
	"github.com/tech/sendico/pkg/model"
	"github.com/tech/sendico/pkg/mservice"
	eapi "github.com/tech/sendico/server/interface/api"
	"github.com/tech/sendico/server/internal/server/papitemplate"
	"go.uber.org/zap"
)

type RecipientAPI struct {
	papitemplate.ProtectedAPI[model.Recipient]
	db recipient.DB
}

func (a *RecipientAPI) Name() mservice.Type {
	return mservice.Recipients
}

func (a *RecipientAPI) Finish(_ context.Context) error {
	return nil
}

func CreateAPI(a eapi.API) (*RecipientAPI, error) {
	dbFactory := func() (papitemplate.ProtectedDB[model.Recipient], error) {
		return a.DBFactory().NewRecipientsDB()
	}

	res := &RecipientAPI{}

	p, err := papitemplate.CreateAPI(a, dbFactory, mservice.Organizations, mservice.Recipients)
	if err != nil {
		return nil, err
	}
	res.ProtectedAPI = *p.
		WithNotifications(res.notification).
		WithNoCreateNotification().
		WithNoUpdateNotification().
		Build()

	if res.db, err = a.DBFactory().NewRecipientsDB(); err != nil {
		res.Logger.Warn("Failed to create recipients database", zap.Error(err))
		return nil, err
	}

	return res, nil
}
