package professor

import (
	"htwkalender/data-manager/model"
	"log/slog"

	commonProf "htwkalender/common/professor"

	"github.com/pocketbase/dbx"
	"github.com/pocketbase/pocketbase"
)

type ProfessorService struct {
	app *pocketbase.PocketBase
}

func NewProfessorService(app *pocketbase.PocketBase) *ProfessorService {
	return &ProfessorService{app: app}
}

func (s *ProfessorService) GetModulesForProfessor(email string) ([]model.ModuleDTO, error) {
	// Extract name from email
	firstName, lastName, err := commonProf.ExtractNameFromEmail(email)
	if err != nil {
		slog.Warn("Failed to extract name from email", "email", email, "error", err)
		return []model.ModuleDTO{}, nil
	}

	slog.Info("Searching for modules for professor", "firstName", firstName, "lastName", lastName, "email", email)

	// First, get all distinct modules with their professors
	type EventProf struct {
		Name      string `db:"Name" json:"name"`
		EventType string `db:"EventType" json:"eventType"`
		Prof      string `db:"Prof" json:"prof"`
		Course    string `db:"course" json:"course"`
		Semester  string `db:"semester" json:"semester"`
		UUID      string `db:"uuid" json:"uuid"`
	}

	var allEvents []EventProf
	err = s.app.DB().
		Select("Name", "EventType", "Prof", "course", "semester", "uuid").
		From("events").
		Where(dbx.NewExp("Prof != ''")).
		GroupBy("Name", "course", "Prof").
		Distinct(true).
		All(&allEvents)

	if err != nil {
		return nil, err
	}

	// Filter events by matching professor name and calculate confidence scores
	var modules []model.ModuleDTO
	seenModules := make(map[string]bool) // key: Name+Course to avoid duplicates

	for _, event := range allEvents {
		score := commonProf.CalculateConfidenceScore(event.Prof, firstName, lastName)
		if score > 0 { // Include all modules with any match
			key := event.Name + "|" + event.Course
			if !seenModules[key] {
				modules = append(modules, model.ModuleDTO{
					Name:            event.Name,
					EventType:       event.EventType,
					Prof:            event.Prof,
					Course:          event.Course,
					Semester:        event.Semester,
					UUID:            event.UUID,
					ConfidenceScore: score,
				})
				seenModules[key] = true
			}
		}
	}

	slog.Info("Found modules for professor", "count", len(modules), "lastName", lastName)
	return modules, nil
}
