package repository

import (
	"context"
	"database/sql"
	"fmt"

	"git.godopu.com/lab/landing_page/backend/internal/models"
)

type LecturesRepository struct {
	db *sql.DB
}

func NewLecturesRepository(db *sql.DB) *LecturesRepository {
	return &LecturesRepository{db: db}
}

func (r *LecturesRepository) GetSemestersWithCourses(ctx context.Context) ([]models.SemesterWithCourses, error) {
	semQuery := `
		SELECT id, year, term
		FROM semesters
		ORDER BY year DESC, CASE term WHEN 'Fall' THEN 1 WHEN 'Spring' THEN 2 ELSE 3 END, id DESC
	`
	semRows, err := r.db.QueryContext(ctx, semQuery)
	if err != nil {
		return nil, fmt.Errorf("query semesters: %w", err)
	}
	defer semRows.Close()

	var semesters []models.SemesterWithCourses
	semMap := make(map[int]int)

	for semRows.Next() {
		var s models.SemesterWithCourses
		if err := semRows.Scan(&s.ID, &s.Year, &s.Term); err != nil {
			return nil, fmt.Errorf("scan semester: %w", err)
		}
		s.Courses = []models.Course{}
		semMap[s.ID] = len(semesters)
		semesters = append(semesters, s)
	}
	if err := semRows.Err(); err != nil {
		return nil, err
	}

	courseQuery := `
		SELECT id, semester_id, code, name_en, name_kr, note, display_order
		FROM courses
		ORDER BY semester_id ASC, display_order ASC, id ASC
	`
	courseRows, err := r.db.QueryContext(ctx, courseQuery)
	if err != nil {
		return nil, fmt.Errorf("query courses: %w", err)
	}
	defer courseRows.Close()

	for courseRows.Next() {
		var c models.Course
		if err := courseRows.Scan(&c.ID, &c.SemesterID, &c.Code, &c.NameEn, &c.NameKr, &c.Note, &c.DisplayOrder); err != nil {
			return nil, fmt.Errorf("scan course: %w", err)
		}
		if idx, exists := semMap[c.SemesterID]; exists {
			semesters[idx].Courses = append(semesters[idx].Courses, c)
		}
	}

	return semesters, courseRows.Err()
}

func (r *LecturesRepository) CreateSemester(ctx context.Context, s models.Semester) (int, error) {
	res, err := r.db.ExecContext(ctx, `
		INSERT INTO semesters (year, term)
		VALUES (?, ?)
	`, s.Year, s.Term)
	if err != nil {
		return 0, fmt.Errorf("insert semester: %w", err)
	}
	id, err := res.LastInsertId()
	return int(id), err
}

func (r *LecturesRepository) UpdateSemester(ctx context.Context, id int, s models.Semester) error {
	res, err := r.db.ExecContext(ctx, `
		UPDATE semesters
		SET year = ?, term = ?
		WHERE id = ?
	`, s.Year, s.Term, id)
	if err != nil {
		return fmt.Errorf("update semester: %w", err)
	}
	rows, err := res.RowsAffected()
	if err == nil && rows == 0 {
		return sql.ErrNoRows
	}
	return err
}

func (r *LecturesRepository) DeleteSemester(ctx context.Context, id int) error {
	res, err := r.db.ExecContext(ctx, `DELETE FROM semesters WHERE id = ?`, id)
	if err != nil {
		return fmt.Errorf("delete semester: %w", err)
	}
	rows, err := res.RowsAffected()
	if err == nil && rows == 0 {
		return sql.ErrNoRows
	}
	return err
}

func (r *LecturesRepository) CreateCourse(ctx context.Context, c models.Course) (int, error) {
	res, err := r.db.ExecContext(ctx, `
		INSERT INTO courses (semester_id, code, name_en, name_kr, note, display_order)
		VALUES (?, ?, ?, ?, ?, ?)
	`, c.SemesterID, c.Code, c.NameEn, c.NameKr, c.Note, c.DisplayOrder)
	if err != nil {
		return 0, fmt.Errorf("insert course: %w", err)
	}
	id, err := res.LastInsertId()
	return int(id), err
}

func (r *LecturesRepository) UpdateCourse(ctx context.Context, id int, c models.Course) error {
	res, err := r.db.ExecContext(ctx, `
		UPDATE courses
		SET code = ?, name_en = ?, name_kr = ?, note = ?, display_order = ?
		WHERE id = ?
	`, c.Code, c.NameEn, c.NameKr, c.Note, c.DisplayOrder, id)
	if err != nil {
		return fmt.Errorf("update course: %w", err)
	}
	rows, err := res.RowsAffected()
	if err == nil && rows == 0 {
		return sql.ErrNoRows
	}
	return err
}

func (r *LecturesRepository) DeleteCourse(ctx context.Context, id int) error {
	res, err := r.db.ExecContext(ctx, `DELETE FROM courses WHERE id = ?`, id)
	if err != nil {
		return fmt.Errorf("delete course: %w", err)
	}
	rows, err := res.RowsAffected()
	if err == nil && rows == 0 {
		return sql.ErrNoRows
	}
	return err
}
