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")
	if fieldErrors, vErr := s.vld.ValidateLoginWithPhoneNumberRequest(ctx, req); vErr != nil {
		return adminserviceparam.LoginWithPhoneNumberResponse{FieldErrors: fieldErrors}, richerror.New(op).WithErr(vErr)
	}
	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.Password, 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{
		Data: adminserviceparam.Data{
			ID:          admin.ID,
			FirstName:   admin.FirstName,
			LastName:    admin.LastName,
			PhoneNumber: admin.PhoneNumber,
			Role:        admin.Role,
			Description: admin.Description,
			Email:       admin.Email,
			Gender:      admin.Gender,
			Status:      admin.Status,
		},
		Tokens: adminserviceparam.Tokens{
			AccessToken:  accessToken,
			RefreshToken: refreshToken,
		},
	}, nil
}
