/**
 * 根据乐读派作品详情恢复创作环节（对应上游 B2 query/work，经 /leai-proxy/work/{id}）
 */
import type { Router } from "vue-router";
import { getWorkDetail } from "@/api/aicreate";
import { STATUS, getRouteByStatus } from "@/utils/aicreate/status";
import { clearExtractDraft } from "@/utils/aicreate/extractDraft";

type AicreateStoreLike = {
  workId: string;
  workDetail: any;
};

function parseWorkPayload(res: unknown): Record<string, any> | null {
  if (!res || typeof res !== "object") return null;
  const r = res as Record<string, any>;
  const inner = r.data !== undefined ? r.data : r;
  if (!inner || typeof inner !== "object") return null;
  return inner as Record<string, any>;
}

/**
 * 拉取作品详情、写入 store 与 le_workId，并按 status 跳转到对应子路由。
 * @returns 是否已成功发起跳转（失败时返回 false，调用方可继续其它恢复逻辑）
 */
export async function resumeLeaiWorkFromApi(
  workId: string,
  router: Router,
  store: AicreateStoreLike,
): Promise<boolean> {
  const id = String(workId || "").trim();
  if (!id) return false;

  try {
    const res = await getWorkDetail(id);
    const work = parseWorkPayload(res);
    if (!work) {
      localStorage.removeItem("le_workId");
      return false;
    }

    const wid = String(work.workId ?? id);
    store.workId = wid;
    store.workDetail = work;
    localStorage.setItem("le_workId", wid);

    const st = Number(work.status);
    if (st === STATUS.FAILED) {
      clearExtractDraft();
      await router.replace({
        name: "PublicCreateCreating",
        query: { workId: wid },
      });
      return true;
    }

    const route = getRouteByStatus(
      work.status as Parameters<typeof getRouteByStatus>[0],
      wid,
    );
    if (!route) {
      clearExtractDraft();
      await router.replace({
        name: "PublicCreateCreating",
        query: { workId: wid },
      });
      return true;
    }

    clearExtractDraft();
    await router.replace(route);
    return true;
  } catch {
    localStorage.removeItem("le_workId");
    return false;
  }
}
