// Change directory.

import { dirname, resolve, isAbsolute } from "path"
import { statSync } from "fs"
import { projectDir } from "@/project"
import { sessionGet, sessionSet } from "@/session"

export default async function (path?: string) {
  const root = projectDir()
  const cwd = sessionGet("cwd") || root

  if (!path || path.trim() === "") {
    sessionSet("cwd", root)
    return
  }

  if (path.endsWith("/")) path = path.slice(0, -1)

  if (path === ".") return
  if (path === "..") {
    if (cwd !== root) {
      const parent = dirname(cwd)
      if (parent.startsWith(root)) {
        sessionSet("cwd", parent)
      }
    }
    return
  }

  const target = isAbsolute(path) ? resolve(path) : resolve(cwd, path)

  if (!target.startsWith(root))
    return ""

  try {
    const stat = statSync(target)
    if (stat.isDirectory()) {
      sessionSet("cwd", target)
      return
    }
  } catch {
  }

  return { error: `${path} doesn't exist` }
}
