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) LoginWithPhoneNumber(ctx context.Context, req adminserviceparam.LoginWithPhoneNumberRequest) (adminserviceparam.LoginWithPhoneNumberResponse, error) {
	const op = richerror.Op("adminservice.LoginWithPhoneNumber")

	admin, err := s.repo.GetAdminByPhoneNumber(ctx, req.PhoneNumber)
	if err != nil {
		return adminserviceparam.LoginWithPhoneNumberResponse{}, richerror.New(op).WithErr(err).WithKind(richerror.KindUnexpected)
	}

	if cErr := CompareHash(admin.GetPassword(), req.Password); cErr != nil {
		return adminserviceparam.LoginWithPhoneNumberResponse{}, richerror.New(op).WithErr(cErr).WithMessage(errmsg.ErrorMsgPhoneNumberOrPassIsIncorrect).WithKind(richerror.KindForbidden)
	}
	authenticableAdmin := entity.Authenticable{
		ID:   admin.ID,
		Role: admin.Role.String(),
	}
	accessToken, aErr := s.auth.CreateAccessToken(authenticableAdmin)
	if aErr != nil {
		return adminserviceparam.LoginWithPhoneNumberResponse{}, richerror.New(op).WithErr(aErr).WithKind(richerror.KindUnexpected)
	}

	refreshToken, rErr := s.auth.CreateRefreshToken(authenticableAdmin)
	if rErr != nil {
		return adminserviceparam.LoginWithPhoneNumberResponse{}, richerror.New(op).WithErr(rErr).WithKind(richerror.KindUnexpected)
	}

	return adminserviceparam.LoginWithPhoneNumberResponse{
		Admin: admin,
		Tokens: adminserviceparam.Tokens{
			AccessToken:  accessToken,
			RefreshToken: refreshToken,
		},
	}, nil
}
