import { archiveAccountThread, deleteArchivedAccountThreadLocalData, renameAccountThread, setAccountThreadPinned } from "./codex-history.js";
import { archiveLogicalThread } from "./thread-archive.js";

export async function resolveThreadRoute(req, url, context) {
  const actionMatch = url.pathname.match(/^\/accounts\/([^/]+)\/threads\/([^/]+)\/(name|pin)$/);
  if (req.method === "PATCH" && actionMatch) {
    const ownerId = decodeURIComponent(actionMatch[1]);
    const threadId = decodeURIComponent(actionMatch[2]);
    const body = await context.readJson(req);
    if (actionMatch[3] === "name") {
      const rename = context.renameAccountThread ?? renameAccountThread;
      const result = await rename(context.config, ownerId, threadId, body.name);
      await context.updateThreadSessionTitle?.(ownerId, threadId, result.name);
      return { status: 200, body: result };
    }
    const setPinned = context.setAccountThreadPinned ?? setAccountThreadPinned;
    return { status: 200, body: await setPinned(context.config, ownerId, threadId, body.pinned) };
  }
  const deleteMatch = url.pathname.match(/^\/accounts\/([^/]+)\/threads\/([^/]+)\/local-delete$/);
  if (req.method === "DELETE" && deleteMatch) {
    const ownerId = decodeURIComponent(deleteMatch[1]);
    const threadId = decodeURIComponent(deleteMatch[2]);
    const deleteArchived = context.deleteArchivedAccountThreadLocalData ?? deleteArchivedAccountThreadLocalData;
    const cleanup = context.deleteThreadLocalData;
    const deleted = await deleteArchived(context.config, ownerId, threadId);
    const local = cleanup ? await cleanup(context.config, ownerId, threadId) : {};
    return { status: 200, body: { ...deleted, ...local } };
  }
  const archiveMatch = url.pathname.match(/^\/accounts\/([^/]+)\/threads\/([^/]+)$/);
  if (req.method === "DELETE" && archiveMatch) {
    const archive = context.archiveLogicalThread ?? archiveLogicalThread;
    const archiveThread = context.archiveAccountThread ?? archiveAccountThread;
    return {
      status: 200,
      body: await archive(
        context.config,
        decodeURIComponent(archiveMatch[1]),
        decodeURIComponent(archiveMatch[2]),
        {
          sessions: context.listSessions?.() ?? [],
          archiveThread,
          listThreads: context.listAccountThreads
        }
      )
    };
  }
  return null;
}
