interface SessionLike {
  metadata: unknown;
  playbackState?: string;
  setActionHandler(action: string, handler: ((details: { seekOffset?: number }) => void) | null): void;
}

export function configureMediaSession(
  session: SessionLike,
  metadata: {
    title: string;
    artist: string;
    album: string;
    artwork?: Array<{ src: string; sizes?: string; type?: string }>;
  },
  handlers: {
    play(): void;
    pause(): void;
    next(): void;
    previous(): void;
    seekBy(seconds: number): void;
  },
  createMetadata: (value: typeof metadata) => unknown = (value) => new MediaMetadata(value),
): void {
  session.metadata = createMetadata(metadata);
  const actions: Array<[string, (details: { seekOffset?: number }) => void]> = [
    ["play", () => handlers.play()],
    ["pause", () => handlers.pause()],
    ["nexttrack", () => handlers.next()],
    ["previoustrack", () => handlers.previous()],
    ["seekbackward", (details) => handlers.seekBy(-(details.seekOffset ?? 15))],
    ["seekforward", (details) => handlers.seekBy(details.seekOffset ?? 15)],
  ];
  for (const [action, handler] of actions) {
    try { session.setActionHandler(action, handler); } catch { /* unsupported action */ }
  }
}
