package universities

import (
	"context"
	"strings"

	"git.bissendorf.co/bissendorf/unifood/m/v2/core/interfaces"
	"git.bissendorf.co/bissendorf/unifood/m/v2/core/interfaces/params"
	"git.bissendorf.co/bissendorf/unifood/m/v2/model/external/stwbremen"
	"git.bissendorf.co/bissendorf/unifood/m/v2/model/resources"
	"git.bissendorf.co/bissendorf/unifood/m/v2/util"
)

type UniversityHandler struct {
	QueryClient interfaces.QueryClient[stwbremen.RestaurantList]
}

func (h *UniversityHandler) Get(ctx context.Context, name string, params params.Container) (*interfaces.ResourceList, error) {
	// Get list of restaurants
	list, err := getRestaurantList(ctx, h.QueryClient)
	if err != nil {
		return nil, err
	}

	// Group restaurants into universities
	unis := util.Group(list, func(i *string) (string, string) {
		parts := strings.SplitN(*i, "/", 2)
		if len(parts) <= 1 {
			return *i, *i
		}

		return parts[0], *i
	})

	// If name is provided remove all other unis
	if name != "" {
		uni, exists := unis[name]
		unis = make(map[string][]string)

		if exists {
			unis[name] = uni
		}
	}

	// Map into resource
	uniItems := make([]resources.University, 0, len(unis))
	for uni, restaurants := range unis {
		uniItems = append(uniItems, resources.University{
			Name:        uni,
			Restaurants: restaurants,
		})
	}

	// Return
	return &interfaces.ResourceList{
		ItemKind: resources.ResourceUniversity,
		Items:    util.Transform(uniItems, func(i *resources.University) interfaces.Resource { return i }),
	}, nil

}

func (h *UniversityHandler) GetParametersForVerb(verb interfaces.Verb) []params.Registration {
	return []params.Registration{}
}
