AddTeamToGithubJob.java

package edu.ucsb.cs156.frontiers.jobs;

import edu.ucsb.cs156.frontiers.entities.Course;
import edu.ucsb.cs156.frontiers.entities.Team;
import edu.ucsb.cs156.frontiers.repositories.TeamRepository;
import edu.ucsb.cs156.frontiers.services.GithubTeamService;
import edu.ucsb.cs156.frontiers.services.GithubTeamService.GithubTeamInfo;
import edu.ucsb.cs156.jobs.services.JobContext;
import edu.ucsb.cs156.jobs.services.JobContextConsumer;
import lombok.Builder;

@Builder
public class AddTeamToGithubJob implements JobContextConsumer {
  Course course;
  String teamName;
  TeamRepository teamRepository;
  GithubTeamService githubTeamService;

  @Override
  public String getScopeType() {
    return "course";
  }

  @Override
  public Long getScopeId() {
    return course.getId();
  }

  @Override
  public void accept(JobContext ctx) throws Exception {
    ctx.log("Starting add team to GitHub job for team: " + teamName);

    if (teamName == null) {
      ctx.log("ERROR: Team has no name");
      return;
    }

    if (course.getOrgName() == null || course.getInstallationId() == null) {
      ctx.log("ERROR: Course has no linked GitHub organization");
      return;
    }

    Team team = teamRepository.findByCourseIdAndName(course.getId(), teamName).orElse(null);
    if (team == null) {
      ctx.log(
          "ERROR: Team with name '"
              + teamName
              + "' not found for course "
              + course.getCourseName());
      return;
    }

    try {
      GithubTeamInfo githubTeamInfo = githubTeamService.createTeamInfo(teamName, course);
      team.setGithubTeamId(githubTeamInfo.id());
      team.setGithubTeamSlug(githubTeamInfo.slug());
      teamRepository.save(team);
      ctx.log(
          "Successfully added team '"
              + team.getName()
              + "' to GitHub with GitHub team ID: "
              + githubTeamInfo.id());
    } catch (Exception e) {
      throw new IllegalStateException("Failed to add team to GitHub: " + e.getMessage(), e);
    }

    if (Boolean.TRUE.equals(team.getIsStaffTeam())) {
      Integer orgId;
      try {
        orgId = githubTeamService.getOrgId(course.getOrgName(), course);
      } catch (Exception e) {
        throw new IllegalStateException(
            "Failed to get organization ID for org: "
                + course.getOrgName()
                + " - "
                + e.getMessage(),
            e);
      }
      StaffTeamGithubSync.addStaffMembers(ctx, course, team, orgId, githubTeamService);
    }

    ctx.log("Done");
  }
}