package repository

import (
	"Yimaru-Backend/internal/domain"
	"context"
)

func (s *Store) GetFullLearningTree(ctx context.Context) ([]domain.TreeCourse, error) {
	rows, err := s.queries.GetFullLearningTree(ctx)
	if err != nil {
		return nil, err
	}

	coursesMap := make(map[int64]*domain.TreeCourse)

	for _, row := range rows {
		course, ok := coursesMap[row.CourseID]
		if !ok {
			course = &domain.TreeCourse{
				ID:         row.CourseID,
				Title:      row.CourseTitle,
				SubCourses: []domain.TreeSubCourse{},
			}
			coursesMap[row.CourseID] = course
		}

		if row.SubCourseID.Valid {
			subCourse := domain.TreeSubCourse{
				ID:    row.SubCourseID.Int64,
				Title: row.SubCourseTitle.String,
				Level: row.SubCourseLevel.String,
			}
			course.SubCourses = append(course.SubCourses, subCourse)
		}
	}

	courses := make([]domain.TreeCourse, 0, len(coursesMap))
	for _, course := range coursesMap {
		courses = append(courses, *course)
	}

	return courses, nil
}
