package db

import (
	"server/internal/models"

	"gorm.io/gorm"
	"gorm.io/gorm/clause"
)

type ClassCourseDTO struct {
	ID         int64  `json:"id"`
	Name       string `json:"name"`
	CourseCode string `json:"courseCode"`
}

func UpsertClassCourses(db *gorm.DB, classRkID int64, items []ClassCourseDTO) error {
	if len(items) == 0 {
		return nil
	}
	rows := make([]models.ClassCourse, 0, len(items))
	for _, it := range items {
		if it.ID <= 0 {
			continue
		}
		rows = append(rows, models.ClassCourse{
			ClassRkID:  classRkID,
			CourseRkID: it.ID,
			Name:       it.Name,
			CourseCode: it.CourseCode,
		})
	}
	if len(rows) == 0 {
		return nil
	}
	return db.Clauses(clause.OnConflict{
		Columns:   []clause.Column{{Name: "class_rk_id"}, {Name: "course_rk_id"}},
		DoUpdates: clause.AssignmentColumns([]string{"name", "course_code", "updated_at"}),
	}).Create(&rows).Error
}

func ListClassCourses(db *gorm.DB, classRkID int64) ([]ClassCourseDTO, error) {
	var rows []models.ClassCourse
	if err := db.Where("class_rk_id = ?", classRkID).Order("name asc").Find(&rows).Error; err != nil {
		return nil, err
	}
	out := make([]ClassCourseDTO, 0, len(rows))
	for _, r := range rows {
		out = append(out, ClassCourseDTO{
			ID:         r.CourseRkID,
			Name:       r.Name,
			CourseCode: r.CourseCode,
		})
	}
	return out, nil
}

func MergeClassCourses(base []ClassCourseDTO, extra []ClassCourseDTO) []ClassCourseDTO {
	merged := make(map[int64]ClassCourseDTO, len(base)+len(extra))
	for _, c := range base {
		if c.ID > 0 {
			merged[c.ID] = c
		}
	}
	for _, c := range extra {
		if c.ID <= 0 {
			continue
		}
		if existing, ok := merged[c.ID]; ok {
			if c.Name != "" {
				existing.Name = c.Name
			}
			if c.CourseCode != "" {
				existing.CourseCode = c.CourseCode
			}
			merged[c.ID] = existing
		} else {
			merged[c.ID] = c
		}
	}
	out := make([]ClassCourseDTO, 0, len(merged))
	for _, c := range merged {
		out = append(out, c)
	}
	return out
}
