import through from "through2"
import fs from "fs"
import path from "path"
import request from "request"

const PLUGIN_NAME = "gulp-file-post"

function filePost(options) {
  if (!options || typeof options !== "object") {
    throw new Error("Missing options!")
  }

  return through.obj(function (file, enc, cb) {
    if (file.isStream()) {
      return cb(new Error("Streaming not supported"))
    }

    if (file.isNull() || file.isDirectory()) {
      return cb(null, file)
    }

    if (file.isBuffer()) {
      const filePath = file.path
      const fileExt = path.extname(filePath).substring(1)

      if (fileExt === "zip") {
        const formData = options.data || {}
        formData["file"] = fs.createReadStream(filePath)
        formData["type"] = fileExt

        const reqOptions = {
          url: options.url,
          formData,
          timeout: options.timeout,
          headers: {
            // Add Authorization header if token provided
            ...(options.token && {
              Authorization: `Bearer ${options.token}`,
            }),
          },
        }

        request.post(reqOptions, (err, resp, body) => {
          if (err) {
            console.error("Error uploading file:", filePath, err)
            return cb(new Error(err))
          }

          if (resp) {
            if (resp.statusCode === 200) {
              console.log("✅ Successfully uploaded:", filePath)
              cb(null, file)
            } else {
              const error = `Upload failed: ${resp.statusCode} ${resp.statusMessage}`
              console.error("❌", error)
              return cb(new Error(error))
            }
          }

          if (options.callback && typeof options.callback === "function") {
            options.callback()
          }
        })
      }
    }
  })
}

export default filePost
