"use client";

import type { SidebarTreeNode } from "@/lib/kernel-sidebar";
import type { MediaAsset } from "@/types/media";

export type FileTreeRowKind = "doc" | "index" | "asset" | "asset-folder";

export type FileTreeRowId =
  | `doc:${string}`
  | `index:${string}`
  | `asset:${string}`
  | `asset-folder:${string}`;

export type ParsedFileTreeRowId =
  | { kind: "doc"; docId: string }
  | { kind: "index"; docId: string }
  | { kind: "asset"; assetId: string }
  | { kind: "asset-folder"; assetId: string };

export function makeDocRowId(docId: string): FileTreeRowId {
  return `doc:${docId}`;
}

export function makeIndexRowId(docId: string): FileTreeRowId {
  return `index:${docId}`;
}

export function makeAssetRowId(assetId: string): FileTreeRowId {
  return `asset:${assetId}`;
}

export function makeAssetFolderRowId(assetId: string): FileTreeRowId {
  return `asset-folder:${assetId}`;
}

export function parseFileTreeRowId(rowId: string): ParsedFileTreeRowId | null {
  const idx = rowId.indexOf(":");
  if (idx <= 0) return null;
  const prefix = rowId.slice(0, idx);
  const rest = rowId.slice(idx + 1);
  if (!rest) return null;
  switch (prefix) {
    case "doc":
      return { kind: "doc", docId: rest };
    case "index":
      return { kind: "index", docId: rest };
    case "asset":
      return { kind: "asset", assetId: rest };
    case "asset-folder":
      return { kind: "asset-folder", assetId: rest };
    default:
      return null;
  }
}

export type FileTreeRow =
  | {
      kind: "doc";
      rowId: FileTreeRowId;
      depth: number;
      docId: string;
      parentDocId: string | null;
      node: SidebarTreeNode;
      hasChildren: boolean;
      isExpanded: boolean;
    }
  | {
      kind: "index";
      rowId: FileTreeRowId;
      depth: number;
      docId: string;
      parentDocId: string;
      node: SidebarTreeNode;
    }
  | {
      kind: "asset-folder";
      rowId: FileTreeRowId;
      depth: number;
      docId: string;
      parentDocId: string;
      asset: MediaAsset;
      hasChildren: boolean;
      isExpanded: boolean;
    }
  | {
      kind: "asset";
      rowId: FileTreeRowId;
      depth: number;
      docId: string;
      parentDocId: string;
      asset: MediaAsset;
    };

export function getFileTreeRowLabel(row: FileTreeRow): string {
  switch (row.kind) {
    case "doc":
      return row.node.title || "无标题";
    case "index":
      return "index.md";
    case "asset-folder": {
      const name = row.asset.file_name || "附件";
      // 思维导图展示为“文件夹”时，去掉 .json 结尾更直观
      return row.asset.asset_type === "mindmap" ? name.replace(/\.json$/i, "") : name;
    }
    case "asset":
      return row.asset.file_name || "附件";
  }
}

export function getOwningDocId(row: FileTreeRow): string {
  switch (row.kind) {
    case "doc":
    case "index":
      return row.docId;
    case "asset-folder":
    case "asset":
      return row.asset.document_id;
  }
}
