import { Task } from "@lit/task";
import type { MediaEngine } from "../../../transcoding/types";
import type { EFVideo } from "../../EFVideo";
import { getLatestMediaEngine } from "../tasks/makeMediaEngineTask";

export const makeVideoSegmentIdTask = (
  host: EFVideo,
): Task<readonly [MediaEngine | undefined, number], number | undefined> => {
  return new Task(host, {
    args: () => [host.mediaEngineTask.value, host.desiredSeekTimeMs] as const,
    onError: (error) => {
      console.error("videoSegmentIdTask error", error);
    },
    onComplete: (_value) => {},
    task: async ([, targetSeekTimeMs], { signal }) => {
      const mediaEngine = await getLatestMediaEngine(host, signal);
      signal.throwIfAborted(); // Abort if a new seek started
      return mediaEngine.computeSegmentId(
        targetSeekTimeMs, // Use captured value, not host.desiredSeekTimeMs
        mediaEngine.getVideoRendition(),
      );
    },
  });
};
