package adminservice

import (
	"context"

	"git.gocasts.ir/ebhomengo/niki/entity"
	adminserviceparam "git.gocasts.ir/ebhomengo/niki/param/admin/admin"
	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 adminserviceparam.RefreshAccessRequest) (adminserviceparam.RefreshAccessResponse, error) {
	const op = "adminservice.RefreshAccess"
	claims, err := s.auth.ParseRefreshToken(req.RefreshToken)
	if err != nil {
		return adminserviceparam.RefreshAccessResponse{}, richerror.New(op).WithKind(richerror.KindInvalid).WithMessage(errmsg.ErrorMsgInvalidOrExpiredJwt)
	}

	admin, err := s.repo.GetAdminByID(ctx, claims.UserID)
	if err != nil {
		return adminserviceparam.RefreshAccessResponse{}, richerror.New(op).WithKind(richerror.KindUnexpected).WithErr(err)
	}
	if admin.Status == entity.AdminInactiveStatus {
		return adminserviceparam.RefreshAccessResponse{}, richerror.New(op).WithKind(richerror.KindForbidden).WithMessage(errmsg.ErrorMsgAdminNotAllowed)
	}

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

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