package grpc

import (
	"context"
	"github.com/pocketbase/pocketbase"
	pb "htwkalender/common/genproto/modules"
	"htwkalender/data-manager/service/db"
)

type ModuleServiceHandler struct {
	app *pocketbase.PocketBase
	pb.UnimplementedModuleServiceServer
}

func (s *ModuleServiceHandler) GetModule(ctx context.Context, in *pb.GetModuleRequest) (*pb.GetModuleResponse, error) {

	s.app.Logger().Info(
		"Protobuf - GetModule",
		"uuid", in.Uuid,
	)

	// get module from database by UUID
	module, err := db.FindModuleByUUID(s.app, in.Uuid)
	if err != nil {
		return nil, err
	}

	events, err := db.FindAllEventsByModule(s.app, module)
	if err != nil {
		return nil, err
	}

	//map module Events to proto struct Events
	protoEvents := make([]*pb.Event, 0)
	for _, event := range events {
		protoEvents = append(protoEvents, eventToProto(&event))
	}
	//map module to proto struct
	protoModule := &pb.Module{
		Uuid:     module.UUID,
		Name:     module.Name,
		Prof:     module.Prof,
		Course:   module.Course,
		Semester: module.Semester,
		Events:   protoEvents,
	}
	// Implement your logic here to fetch module data based on the UUID
	// Example response
	return &pb.GetModuleResponse{
		Module: protoModule,
	}, nil
}

func (s *ModuleServiceHandler) GetEventsForModules(ctx context.Context, in *pb.GetModulesRequest) (*pb.GetEventsResponse, error) {

	s.app.Logger().Info(
		"Protobuf - GetEventsForModules",
		"uuids", in.Uuids,
	)

	events, err := db.GetPlanForModules(s.app, in.Uuids)
	if err != nil {
		return nil, err
	}

	return &pb.GetEventsResponse{
		Events: eventsToProto(events),
	}, nil
}
