package grpc

import (
	"context"
	"fmt"
	"log"
	"net"

	pb "git.gocasts.ir/ebhomengo/niki/contract/goprotobuf/account"
	"git.gocasts.ir/ebhomengo/niki/domain/account/service"
	"git.gocasts.ir/ebhomengo/niki/pkg/grpc"
)

type Server struct {
	server     *grpc.RPCServer
	accountSvc service.Service
	pb.UnimplementedAccountServiceServer
}

func New(server *grpc.RPCServer, accountSvc service.Service) Server {
	return Server{
		server:     server,
		accountSvc: accountSvc,
	}
}

func (s Server) SendOtp(ctx context.Context, req *pb.SendOtpRequest) (*pb.SendOtpResponse, error) {
	err := s.accountSvc.SendOTP(ctx, req.PhoneNumber)
	if err != nil {
		return nil, err
	}

	return &pb.SendOtpResponse{}, nil
}

func (s Server) LoginOrRegister(ctx context.Context, req *pb.LoginOrRegisterRequest) (*pb.LoginOrRegisterResponse, error) {
	res := &pb.LoginOrRegisterResponse{}
	driver, err := s.accountSvc.LoginOrRegisterDriver(ctx, req.PhoneNumber, req.VerifyCode)
	if err != nil {
		return nil, err
	}

	id := uint64(driver.ID)

	res.Id = id
	res.PhoneNumber = driver.PhoneNumber

	return res, nil

}

func (s Server) Start() error {
	listener, err := net.Listen(s.server.Config.NetworkType, fmt.Sprintf(":%d", s.server.Config.Port))

	if err != nil {
		return err
	}

	accountSvcServer := Server{}

	pb.RegisterAccountServiceServer(s.server.Server, &accountSvcServer)

	if err := s.server.Server.Serve(listener); err != nil {
		log.Fatalf("failed to serve: %v", err)
	}

	return nil
}
