package grpc

import (
	"context"
	pb "htwkalender/common/genproto/modules"
	"htwkalender/data-manager/service/db"

	"github.com/pocketbase/pocketbase"
)

type FeedServiceHandler struct {
	app *pocketbase.PocketBase
	pb.UnimplementedFeedServiceServer
}

func (s *FeedServiceHandler) GetFeed(ctx context.Context, in *pb.GetFeedRequest) (*pb.GetFeedResponse, error) {

	s.app.Logger().Info(
		"Protobuf - GetFeed",
		"uuid", in.Id,
	)

	// get feed from database by UUID
	feed, err := db.FindFeedByToken(s.app, in.Id)
	if err != nil {
		return nil, err
	}

	pbFeed := feedToProto(feed)

	// If feed has a user linked, fetch the user's email
	if feed.User != "" {
		user, err := s.app.FindRecordById("users", feed.User)
		if err == nil && user != nil {
			pbFeed.UserEmail = user.Email()
		}
	}

	return &pb.GetFeedResponse{
		Feed: pbFeed,
	}, nil
}
