package repository import ( "context" "fmt" ) // ReorderPrograms sets sort_order to 1..n in the given order (transactional). func (s *Store) ReorderPrograms(ctx context.Context, orderedIDs []int64) error { tx, err := s.conn.Begin(ctx) if err != nil { return err } defer func() { _ = tx.Rollback(ctx) }() for i, id := range orderedIDs { tag, err := tx.Exec(ctx, `UPDATE programs SET sort_order = $1, updated_at = CURRENT_TIMESTAMP WHERE id = $2`, int32(i+1), id) if err != nil { return err } if tag.RowsAffected() == 0 { return fmt.Errorf("program id %d not found", id) } } return tx.Commit(ctx) } // ReorderCoursesInProgram sets sort_order for courses under programID (transactional). func (s *Store) ReorderCoursesInProgram(ctx context.Context, programID int64, orderedIDs []int64) error { tx, err := s.conn.Begin(ctx) if err != nil { return err } defer func() { _ = tx.Rollback(ctx) }() for i, id := range orderedIDs { tag, err := tx.Exec(ctx, ` UPDATE courses SET sort_order = $1, updated_at = CURRENT_TIMESTAMP WHERE id = $2 AND program_id = $3`, int32(i+1), id, programID) if err != nil { return err } if tag.RowsAffected() == 0 { return fmt.Errorf("course id %d not in program %d", id, programID) } } return tx.Commit(ctx) } // ReorderModulesInCourse sets sort_order for modules under courseID (transactional). func (s *Store) ReorderModulesInCourse(ctx context.Context, courseID int64, orderedIDs []int64) error { tx, err := s.conn.Begin(ctx) if err != nil { return err } defer func() { _ = tx.Rollback(ctx) }() for i, id := range orderedIDs { tag, err := tx.Exec(ctx, ` UPDATE modules SET sort_order = $1, updated_at = CURRENT_TIMESTAMP WHERE id = $2 AND course_id = $3`, int32(i+1), id, courseID) if err != nil { return err } if tag.RowsAffected() == 0 { return fmt.Errorf("module id %d not in course %d", id, courseID) } } return tx.Commit(ctx) }