package paymethodsimp

import (
	"context"

	"github.com/tech/sendico/pkg/db/paymethod"
	"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.PaymentMethod]
	db paymethod.DB
}

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

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

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

	res := &RecipientAPI{}

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

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

	return res, nil
}
