package repositories

import (
	"database/sql"
	"errors"
	"fmt"
	"log"
	"officeHours/models"
)

// A struct to hold the db connection
type CourseRepo struct {
	db *sql.DB
}

func NewCourseRepo(db *sql.DB) *CourseRepo {
	return &CourseRepo{
		db: db,
	}
}

func (r *CourseRepo) FindByName(name string) (models.Course, error) {
	return r.getFromRow(r.db.QueryRow("SELECT * FROM course WHERE name=?", name))
}

func (r *CourseRepo) FindById(id int) (models.Course, error) {
	return r.getFromRow(r.db.QueryRow("SELECT * FROM course WHERE id=?", id))
}

func (r *CourseRepo) GetAll() ([]models.Course, error) {
	rows, err := r.db.Query("SELECT * FROM course ORDER BY name ASC")
	if err != nil {
		log.Printf("error getting all courses: %s", err.Error())
		return nil, err
	}
	defer rows.Close()

	return r.getFromRows(rows)
}

// Helper function to get a course from multiple SQL result rows
func (r *CourseRepo) getFromRows(rows *sql.Rows) ([]models.Course, error) {
	var courses []models.Course
	for rows.Next() {
		var course models.Course
		if err := rows.Scan(&course.Id, &course.Name); err != nil {
			log.Printf("Error scanning course row: %s", err.Error())
			return courses, err
		}
		courses = append(courses, course)
	}
	return courses, nil
}

// Helper function to get a course from an SQL result row
func (r *CourseRepo) getFromRow(row *sql.Row) (models.Course, error) {
	var course models.Course
	if err := row.Scan(&course.Id, &course.Name); err != nil {
		err = fmt.Errorf("error getting course row: %w", err)
		if !errors.Is(err, sql.ErrNoRows) {
			log.Print(err.Error())
		}
		return models.Course{}, err
	}
	return course, nil
}
