package billing

import (
	"context"

	"github.com/gogo/protobuf/types"
	"github.com/pingcap/dbaas/central/db/entity"
	"github.com/pingcap/dbaas/central/model/billing"
	"github.com/pingcap/dbaas/central/service"
	"github.com/tidbcloud/idl/pbgen/proto/central"
)

type billingService struct {
	central.UnimplementedBillingServiceServer
	service.OperationsService
	model billing.Model
}

var _ central.BillingServiceServer = (*billingService)(nil)

func NewService(s service.OperationsService, model billing.Model) central.BillingServiceServer {
	return &billingService{OperationsService: s, model: model}
}

func (b *billingService) userContext(ctx context.Context) billing.Context {
	return b.model.User(b.CurrentUser(ctx))
}

func (b *billingService) GetCredits(c context.Context, req *central.OrgIdReq) (*central.Credits, error) {
	userContext := b.userContext(c)
	orgID := entity.ID(req.OrgId)
	err := userContext.CheckOrgID(orgID)
	if err != nil {
		return nil, err
	}
	err = userContext.CheckIfOwnerOrBillingAdmin()
	if err != nil {
		return nil, err
	}

	credits, err := userContext.GetPOCCredits()
	if err != nil {
		return nil, err
	}
	return &central.Credits{
		Amount: credits,
	}, nil
}

func (b *billingService) SetupIntentConfirm(c context.Context, req *central.OrgIdReq) (*types.Empty, error) {
	userContext := b.userContext(c)
	return &types.Empty{}, userContext.ConfirmOnDemandByStripeSetupIntent()
}

func (b *billingService) GetCreditsHistory(c context.Context, req *central.OrgIdReq) (*central.CreditsHistory, error) {
	userContext := b.userContext(c)
	orgID := entity.ID(req.OrgId)
	err := userContext.CheckOrgID(orgID)
	if err != nil {
		return nil, err
	}
	err = userContext.CheckIfOwnerOrBillingAdmin()
	if err != nil {
		return nil, err
	}

	creditsHistory, err := userContext.GetPOCCreditsHistory()
	if err != nil {
		return nil, err
	}
	return creditsHistory, nil
}
