package customer_clients

import (
	"context"
	"go.uber.org/zap"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"penahub.gitlab.yandexcloud.net/pena-services/customer/internal/proto/customer"
)

type CustomersClientDeps struct {
	Logger              *zap.Logger
	CustomerServiceHost string
}

type CustomersClient struct {
	logger              *zap.Logger
	customerServiceHost string
}

func NewCustomersClient(deps CustomersClientDeps) *CustomersClient {
	return &CustomersClient{
		logger:              deps.Logger,
		customerServiceHost: deps.CustomerServiceHost,
	}
}

func (receiver *CustomersClient) SetVerifyAccount(ctx context.Context, userId string, accountStatus string) (*customer.Account, error) {
	connection, err := grpc.Dial(receiver.customerServiceHost, grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		receiver.logger.Error("failed to connect on <SetVerifyAccount> of <CustomerClient>", zap.Error(err), zap.String("customer host", receiver.customerServiceHost))
		return nil, err
	}
	defer func() {
		if closeErr := connection.Close(); closeErr != nil {
			receiver.logger.Error("failed to close connection on <SetVerifyAccount> of <CustomerClient>", zap.Error(closeErr))
		}
	}()

	client := customer.NewCustomerServiceClient(connection)

	account, err := client.SetAccountVerificationStatus(ctx, &customer.SetVerificationReq{
		UserID: userId,
		Status: customer.AccountStatus(customer.AccountStatus_value[accountStatus]),
	})
	if err != nil {
		receiver.logger.Error("failed Set Account Verification Status on <SetVerifyAccount> of <CustomerClient>", zap.Error(err))
		return nil, err
	}

	return account, nil
}

type InsertHistoryDeps struct {
	// id user
	UserID string
	// comment in note, example: Успешная оплата корзины
	Comment string
	// key: example end
	Key string
}

func (receiver *CustomersClient) InsertHistory(ctx context.Context, deps InsertHistoryDeps) error {
	connection, err := grpc.Dial(receiver.customerServiceHost, grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		receiver.logger.Error("failed to connect on <InsertHistory> of <CustomerClient>", zap.Error(err), zap.String("customer host", receiver.customerServiceHost))
		return err
	}
	defer func() {
		if closeErr := connection.Close(); closeErr != nil {
			receiver.logger.Error("failed to close connection on <InsertHistory> of <CustomerClient>", zap.Error(closeErr))
		}
	}()

	client := customer.NewCustomerServiceClient(connection)

	_, err = client.InsertHistory(ctx, &customer.History{
		UserID:  deps.UserID,
		Comment: deps.Comment,
		Key:     deps.Key,
	})

	if err != nil {
		receiver.logger.Error("failed insert history on <InsertHistory> of <CustomerClient>", zap.Error(err))
		return err
	}

	return nil
}
