import { BatchGetBuildsCommand, CodeBuildClient, StartBuildCommand } from "@aws-sdk/client-codebuild";

const client = new CodeBuildClient({});
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

export const handler = async () => {
  const startCmd = new StartBuildCommand({ projectName: process.env.PROJECT_NAME });
  const { build } = await client.send(startCmd);
  const buildId = build.id;

  if (!buildId) {
    throw new Error("Failed to start CodeBuild job.");
  }
  console.log("Started CodeBuild job with ID:", buildId);

  while (true) {
    const getStatusCmd = new BatchGetBuildsCommand({ ids: [buildId] });
    const { builds } = await client.send(getStatusCmd);
    const status = builds[0]?.buildStatus;

    console.log("Current build status:", status);

    if (status === "SUCCEEDED") {
      console.log("Migration completed successfully.");
      break;
    }

    if (status === "FAILED" || status === "FAULT" || status === "STOPPED" || status === "TIMED_OUT") {
      throw new Error(`Migration failed with status: ${status}.`);
    }

    await sleep(15000);
  }
};
