const express = require('express');
const multer = require('multer');
const fs = require('fs');
const path = require('path');

const app = express();
const PORT = process.env.PORT || 3000;

const ROOT = __dirname;
const UPLOADS_DIR = path.join(ROOT, 'uploads');
const DETAILS_FILE = path.join(ROOT, 'imagedetails.json');

// ensure folders/files exist
fs.mkdirSync(UPLOADS_DIR, { recursive: true });
if (!fs.existsSync(DETAILS_FILE)) fs.writeFileSync(DETAILS_FILE, '[]', 'utf8');

// Multer setup
const storage = multer.diskStorage({
	destination: function (req, file, cb) {
		cb(null, UPLOADS_DIR);
	},
	filename: function (req, file, cb) {
		// prefix with timestamp to avoid collisions
		const safe = file.originalname.replace(/\s+/g, '_');
		cb(null, Date.now() + '_' + safe);
	}
});

function fileFilter(req, file, cb) {
	if (file.mimetype && file.mimetype.startsWith('image/')) cb(null, true);
	else cb(new Error('Only image files are allowed'));
}

const upload = multer({ storage, fileFilter, limits: { fileSize: 10 * 1024 * 1024 } }); // 10MB

app.use(express.json());
// serve the uploads folder under a configurable URL (default: /uploads)
const UPLOADS_URL = process.env.UPLOADS_URL || '/uploads';
app.use(UPLOADS_URL, express.static(UPLOADS_DIR));
// also keep legacy/alternate path available for environments that expect /uploadfiles
if (UPLOADS_URL !== '/uploadfiles') {
	app.use('/uploadfiles', express.static(UPLOADS_DIR));
}

// serve the static client UI (public folder)
app.use(express.static(path.join(__dirname, 'public')));

app.get('/', (req, res) => res.send('Event Image Uploader is running'));

app.post('/upload', upload.single('image'), (req, res) => {
	if (!req.file) return res.status(400).json({ error: 'No file uploaded' });

	// eventName should be provided as a text field in the multipart form
	const eventNameRaw = (req.body && req.body.eventName) ? String(req.body.eventName) : '';
	const eventName = eventNameRaw.trim();
	if (!eventName) return res.status(400).json({ error: 'Missing eventName field' });

	const meta = {
		filename: req.file.filename,
		originalname: req.file.originalname,
		path: `uploads/${req.file.filename}`,
		size: req.file.size,
		mimetype: req.file.mimetype,
		uploadedAt: new Date().toISOString(),
		eventName: eventName
	};

	try {
		const raw = fs.readFileSync(DETAILS_FILE, 'utf8') || '[]';
		const arr = JSON.parse(raw);
		arr.push(meta);
		fs.writeFileSync(DETAILS_FILE, JSON.stringify(arr, null, 2), 'utf8');
		return res.json({ ok: true, meta });
	} catch (err) {
		console.error('Failed to save metadata', err);
		return res.status(500).json({ error: 'Failed to save metadata' });
	}
});

app.get('/images', (req, res) => {
	try {
		const raw = fs.readFileSync(DETAILS_FILE, 'utf8') || '[]';
		const arr = JSON.parse(raw);
		// sort by eventName (ascending, case-insensitive), then uploadedAt (newest first)
		arr.sort((a, b) => {
			const aName = (a.eventName || '').toString().toLowerCase();
			const bName = (b.eventName || '').toString().toLowerCase();
			if (aName < bName) return -1;
			if (aName > bName) return 1;
			const da = new Date(a.uploadedAt || a.uploadDate || 0).getTime();
			const db = new Date(b.uploadedAt || b.uploadDate || 0).getTime();
			return db - da;
		});
		res.json(arr);
	} catch (err) {
		res.status(500).json({ error: 'Failed to read metadata' });
	}
});

// DELETE an uploaded image by filename (safe: uses path.basename)
app.delete('/images/:filename', (req, res) => {
	try {
		const filename = path.basename(req.params.filename);
		if (!filename) return res.status(400).json({ error: 'Missing filename' });

		const filePath = path.join(UPLOADS_DIR, filename);
		if (!fs.existsSync(filePath)) return res.status(404).json({ error: 'File not found' });

		// remove the file
		fs.unlinkSync(filePath);

		// remove metadata entry
		const raw = fs.readFileSync(DETAILS_FILE, 'utf8') || '[]';
		let arr = JSON.parse(raw);
		const before = arr.length;
		arr = arr.filter(item => item.filename !== filename);
		if (arr.length !== before) {
			fs.writeFileSync(DETAILS_FILE, JSON.stringify(arr, null, 2), 'utf8');
		}

		return res.json({ ok: true, filename });
	} catch (err) {
		console.error('Error deleting image:', err);
		return res.status(500).json({ error: 'Failed to delete image' });
	}
});

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

