// JavaScript Documentimport express from "express";
import path from "path";
import fs from "fs";
import helmet from "helmet";
import multer from "multer";
import sharp from "sharp";
import basicAuth from "basic-auth";

const app = express();

// ====== CONFIG (set these as env vars) ======
const PORT = process.env.PORT || 5050;
const UPLOAD_USER = process.env.UPLOAD_USER || "team";
const UPLOAD_PASS = process.env.UPLOAD_PASS || "change-me";

// Resolve paths relative to this file
const __dirname = path.dirname(new URL(import.meta.url).pathname);
const root = path.resolve(__dirname, "..");
const publicDir = path.join(root, "public");
const fullDir = path.join(publicDir, "uploads", "full");
const thumbDir = path.join(publicDir, "uploads", "thumbs");
const metaFile = path.join(publicDir, "uploads", "gallery.json");

// Ensure dirs exist
fs.mkdirSync(fullDir, { recursive: true });
fs.mkdirSync(thumbDir, { recursive: true });
if (!fs.existsSync(metaFile)) fs.writeFileSync(metaFile, "[]", "utf8");

// Security headers
app.use(helmet({ crossOriginResourcePolicy: { policy: "cross-origin" } }));

// Serve public static files (community page, thumbs, etc.)
app.use(express.static(publicDir, { extensions: ["html"] }));

// ====== Basic Auth middleware for /upload + /api/upload ======
function requireAuth(req, res, next) {
  const creds = basicAuth(req);
  if (!creds || creds.name !== UPLOAD_USER || creds.pass !== UPLOAD_PASS) {
    res.set("WWW-Authenticate", 'Basic realm="Knott4Gotten Upload"');
    return res.status(401).send("Authentication required.");
  }
  next();
}

// Protect upload page route
app.get("/upload", requireAuth, (req, res) => {
  res.sendFile(path.join(publicDir, "upload.html"));
});

// ====== Multer config (memory storage, size limits) ======
const upload = multer({
  storage: multer.memoryStorage(),
  limits: { fileSize: 10 * 1024 * 1024 }, // 10MB
  fileFilter: (req, file, cb) => {
    const ok = ["image/jpeg", "image/png", "image/webp"].includes(file.mimetype);
    cb(ok ? null : new Error("Only JPG, PNG, or WebP allowed."), ok);
  }
});

// Utility: safe filename
function makeName() {
  const t = new Date().toISOString().replace(/[:.]/g, "-");
  const rnd = Math.random().toString(16).slice(2, 10);
  return `${t}_${rnd}`;
}

// Read/write gallery metadata
function readGallery() {
  return JSON.parse(fs.readFileSync(metaFile, "utf8"));
}
function writeGallery(items) {
  fs.writeFileSync(metaFile, JSON.stringify(items, null, 2), "utf8");
}

// ====== Upload endpoint ======
app.post("/api/upload", requireAuth, upload.single("photo"), async (req, res) => {
  try {
    if (!req.file) return res.status(400).json({ error: "No file uploaded." });

    // Optional caption sanitize
    const caption = (req.body.caption || "").toString().trim().slice(0, 120);

    const base = makeName();
    const fullName = `${base}.jpg`;
    const thumbName = `${base}_thumb.jpg`;

    const fullPath = path.join(fullDir, fullName);
    const thumbPath = path.join(thumbDir, thumbName);

    // Convert to JPEG and resize for "full" (keeps it web-friendly)
    const img = sharp(req.file.buffer).rotate(); // rotate based on EXIF
    await img
      .resize({ width: 2000, withoutEnlargement: true })
      .jpeg({ quality: 82 })
      .toFile(fullPath);

    // Thumbnail
    await img
      .resize({ width: 600, withoutEnlargement: true })
      .jpeg({ quality: 75 })
      .toFile(thumbPath);

    const items = readGallery();
    items.unshift({
      id: base,
      caption,
      fullUrl: `/uploads/full/${fullName}`,
      thumbUrl: `/uploads/thumbs/${thumbName}`,
      createdAt: new Date().toISOString()
    });
    writeGallery(items);

    res.json({ ok: true });
  } catch (err) {
    const msg = err?.message || "Upload failed.";
    res.status(400).json({ error: msg });
  }
});

// ====== Public gallery feed ======
app.get("/api/gallery", (req, res) => {
  res.json(readGallery());
});

// Convenience route
app.get("/community", (req, res) => {
  res.sendFile(path.join(publicDir, "community.html"));
});

app.listen(PORT, () => {
  console.log(`Upload server running on http://localhost:${PORT}`);
});