package marketplace

import (
	"context"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	pb "sipro-mps/api/generated/v1/marketplace"
	"sipro-mps/internal/marketplace/db"
)

// AdapterGRPC implements the gRPC server for the Marketplace service.
type AdapterGRPC struct {
	pb.UnimplementedMarketplaceServiceServer
	repo Repository
}

func NewAdapterGRPC(repo Repository) *AdapterGRPC {
	return &AdapterGRPC{
		repo: repo,
	}
}
func RegisterAdapterGRPC(server *grpc.Server, conn db.DBTX) (*Repository, error) {
	//conn, err := pgx.Connect(context.Background(), "postgresql://postgres:GjitkeYf%5Beq@/sipro?host=/run/postgresql")
	//if err != nil {
	//	return nil, err
	//}
	repo := NewDBRepository(conn)
	adapter := NewAdapterGRPC(repo)
	pb.RegisterMarketplaceServiceServer(server, adapter)
	return &repo, nil
}

func (g *AdapterGRPC) GetMarketplaceById(ctx context.Context, r *pb.GetMarketplaceByIdRequest) (*pb.Marketplace, error) {
	mp, err := g.repo.GetMarketplaceByID(ctx, int(r.MarketplaceId))
	if err != nil {
		return nil, status.Errorf(codes.Internal, "failed to get marketplace by ID: %v", err)
	}

	return &pb.Marketplace{
		Id:              uint64(uint32(mp.ID)),
		BaseMarketplace: uint32(int32(mp.BaseMarketplace)),
		AuthData:        mp.AuthData,
		WarehouseId:     mp.WarehouseID,
	}, nil
}
