import { existsSync, mkdirSync, writeFileSync } from "node:fs"
import { resolve } from "node:path"

const SYNC_PATH = "/__exxat/builder-sync"

/**
 * Vite dev-only plugin: writes `public/tenant-products.json` when the builder
 * app POSTs catalog + productData + hub storage snapshots.
 *
 * Pair with BuilderDevSync in the app shell (enabled when authoring).
 *
 * @param {object} [options]
 * @param {string} [options.catalogPath] Defaults to `<root>/public/tenant-products.json`.
 * @returns {import('vite').Plugin}
 */
export function exxatBuilderDevSync(options = {}) {
  return {
    name: "exxat-builder-dev-sync",
    apply: "serve",
    configureServer(server) {
      server.middlewares.use(SYNC_PATH, (req, res, next) => {
        if (req.method !== "POST") {
          next()
          return
        }

        let body = ""
        req.on("data", chunk => {
          body += chunk
        })
        req.on("end", () => {
          let parsed
          try {
            parsed = JSON.parse(body)
          } catch {
            res.statusCode = 400
            res.end("Invalid JSON")
            return
          }

          if (!Array.isArray(parsed?.catalog) || parsed.catalog.length === 0) {
            res.statusCode = 409
            res.end("Refusing to overwrite catalog with empty payload")
            return
          }

          const root = server.config.root
          const target =
            options.catalogPath ?? resolve(root, "public/tenant-products.json")
          mkdirSync(resolve(target, ".."), { recursive: true })
          writeFileSync(target, `${body.trimEnd()}\n`, "utf8")

          res.statusCode = 200
          res.setHeader("Content-Type", "application/json")
          res.end(JSON.stringify({ ok: true, path: target }))
        })
      })
    },
  }
}

/** @param {string} root */
export function exxatBuilderDevSyncCatalogExists(root) {
  return existsSync(resolve(root, "public/tenant-products.json"))
}
