package benefactorservice

import (
	"context"

	"git.gocasts.ir/ebhomengo/niki/entity"
	benefactorparam "git.gocasts.ir/ebhomengo/niki/param/benefactor/benefactor"
	errmsg "git.gocasts.ir/ebhomengo/niki/pkg/err_msg"
	richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error"
)

func (s Service) RefreshAccess(ctx context.Context, req benefactorparam.RefreshAccessRequest) (benefactorparam.RefreshAccessResponse, error) {
	const op = "adminservice.RefreshAccess"
	claims, err := s.auth.ParseRefreshToken(req.RefreshToken)
	if err != nil {
		return benefactorparam.RefreshAccessResponse{}, richerror.New(op).WithKind(richerror.KindInvalid).WithMessage(errmsg.ErrorMsgInvalidOrExpiredJwt)
	}

	benefactor, err := s.repo.GetByID(ctx, claims.UserID)
	if err != nil {
		return benefactorparam.RefreshAccessResponse{}, richerror.New(op).WithKind(richerror.KindUnexpected).WithErr(err)
	}
	if benefactor.Status == entity.BenefactorInactiveStatus {
		return benefactorparam.RefreshAccessResponse{}, richerror.New(op).WithKind(richerror.KindForbidden).WithMessage(errmsg.ErrorMsgUserNotAllowed)
	}

	accessToken, err := s.auth.CreateAccessToken(entity.Authenticable{
		ID:   claims.UserID,
		Role: claims.Role,
	})
	if err != nil {
		return benefactorparam.RefreshAccessResponse{}, richerror.New(op).WithKind(richerror.KindUnexpected).WithErr(err)
	}

	return benefactorparam.RefreshAccessResponse{AccessToken: accessToken}, nil
}
