package invitationimp

import (
	"context"

	api "github.com/tech/sendico/pkg/api/http"
	"github.com/tech/sendico/pkg/db/account"
	"github.com/tech/sendico/pkg/db/invitation"
	"github.com/tech/sendico/pkg/db/organization"
	"github.com/tech/sendico/pkg/db/transaction"
	"github.com/tech/sendico/pkg/messaging"
	"github.com/tech/sendico/pkg/model"
	"github.com/tech/sendico/pkg/mservice"
	"github.com/tech/sendico/server/interface/accountservice"
	eapi "github.com/tech/sendico/server/interface/api"
	mutil "github.com/tech/sendico/server/internal/mutil/param"
	"github.com/tech/sendico/server/internal/server/papitemplate"
	"go.uber.org/zap"
)

type InvitationAPI struct {
	papitemplate.ProtectedAPI[model.Invitation]
	db         invitation.DB
	irh        mutil.ParamHelper
	tf         transaction.Factory
	adb        account.DB
	odb        organization.DB
	accService accountservice.AccountService
	producer   messaging.Producer
}

func (a *InvitationAPI) Name() mservice.Type {
	return mservice.Invitations
}

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

func CreateAPI(a eapi.API) (*InvitationAPI, error) {
	dbFactory := func() (papitemplate.ProtectedDB[model.Invitation], error) {
		return a.DBFactory().NewInvitationsDB()
	}

	res := &InvitationAPI{
		irh:      mutil.CreatePH("invitation"),
		tf:       a.DBFactory().TransactionFactory(),
		producer: a.Register().Messaging().Producer(),
	}

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

	if res.db, err = a.DBFactory().NewInvitationsDB(); err != nil {
		res.Logger.Warn("Failed to create invitation database", zap.Error(err))
		return nil, err
	}
	if res.adb, err = a.DBFactory().NewAccountDB(); err != nil {
		res.Logger.Warn("Failed to create accounts database", zap.Error(err))
		return nil, err
	}
	if res.odb, err = a.DBFactory().NewOrganizationDB(); err != nil {
		res.Logger.Warn("Failed to create organizations database", zap.Error(err))
		return nil, err
	}
	if res.accService, err = accountservice.NewAccountService(
		res.Logger,
		a.DBFactory(),
		a.Permissions().Enforcer(),
		a.Permissions().Manager().Role(),
		&a.Config().Mw.Password); err != nil {
		res.Logger.Warn("Failed to create account service", zap.Error(err))
		return nil, err
	}

	a.Register().Handler(mservice.Invitations, res.irh.AddRef("/public"), api.Get, res.public)
	a.Register().Handler(mservice.Invitations, res.irh.AddRef("/accept"), api.Put, res.accept)
	a.Register().Handler(mservice.Invitations, res.irh.AddRef("/decline"), api.Delete, res.decline)

	return res, nil
}
