import { join } from "path"
import { projectDir } from "@/project"
import { sessionGet } from "@/session"

export default function () {
  const project = sessionGet("project")
  if (!project) return { error: "No project loaded" }

  return <>
    <form method="post" action="/upload">
      <input type="file" name="file" required={true} />
      <br />
      <br />
      <input type="submit" value="Upload" />
    </form>
  </>
}

export async function POST(c: Context) {
  const cwd = sessionGet("cwd") || projectDir()
  if (!cwd) throw "No project loaded"

  const form = await c.req.formData()
  const file = form.get("file")

  if (file && file instanceof File) {
    const arrayBuffer = await file.arrayBuffer()
    await Bun.write(join(cwd, file.name), arrayBuffer)

    return `Uploaded ${file.name}`
  }

  return { error: "No file received" }
}
