import AWS from "aws-sdk";
import formidable from "formidable";
import fs from "fs";
import { apiHandler, db } from "@/helpers/api";

export const config = { api: { bodyParser: false } }; 

const s3 = new AWS.S3({
	accessKeyId: process.env.AWS_ACCESS_KEY_ID || "AKIA2AFW3Y3GU5WK2Y6G",
	secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY || "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",
	region: "eu-north-1",
});

export default apiHandler({
	get: getBanners,
	post: uploadBanner,
	put: updateBanners,
	delete: deleteBanner,
});

async function requireAdmin(req) {
	if (!db.initialized) await db.initialize();
	const user = await db.User.findByPk(req.userID);
	if (!user || user.admin < 1) throw new Error("Unauthorized");
}

async function saveSetting(name, value) {
    const existing = await db.Settings.findOne({ where: { name } });
    if (existing) {
        await existing.update({ value });
    } else {
        await db.Settings.create({ name, value });
    }
}

async function getBanners(req, res) {
	await requireAdmin(req);
	if (!db.initialized) await db.initialize();

	const setting = await db.Settings.findOne({ where: { name: "bannerImages" } });
	const banners = setting ? JSON.parse(setting.value || "[]") : [];

	return res.status(200).json({ banners });
}

async function uploadBanner(req, res) {
	await requireAdmin(req);

	const form = formidable({ maxFileSize: 10 * 1024 * 1024 }); // max 10MB

	const [fields, files] = await new Promise((resolve, reject) => {
		form.parse(req, (err, fields, files) => {
			if (err) reject(err);
			else resolve([fields, files]);
		});
	});

	const file = files.image?.[0] || files.image;
	if (!file) return res.status(400).json({ error: "Nicio imagine trimisă." });

	const allowedTypes = ["image/jpeg", "image/png", "image/webp", "image/gif"];
	if (!allowedTypes.includes(file.mimetype)) {
		return res.status(400).json({ error: "Doar imagini JPG, PNG, WEBP sau GIF." });
	}

	const fileBuffer = fs.readFileSync(file.filepath);
	const ext = file.originalFilename?.split(".").pop() || "jpg";
	const fileName = `banners/${Date.now()}_${Math.random().toString(36).slice(2)}.${ext}`;

	const uploadResult = await s3
		.upload({
			Bucket: "emagyl",
			Key: fileName,
			Body: fileBuffer,
			ContentType: file.mimetype,
			ACL: "public-read",
		})
		.promise();

	const url = uploadResult.Location.replace(
		"https://emagyl.s3.eu-north-1.amazonaws.com",
		"https://d372xxb7fb1cod.cloudfront.net",
	);

	// Adaugă la lista existentă
	if (!db.initialized) await db.initialize();
	const setting = await db.Settings.findOne({ where: { name: "bannerImages" } });
	const banners = setting ? JSON.parse(setting.value || "[]") : [];

	const newBanner = {
		id: Date.now().toString(),
		url,
		title: fields.title?.[0] || fields.title || "",
		active: true,
		createdAt: new Date().toISOString(),
	};

	banners.push(newBanner);

	await saveSetting("bannerImages", JSON.stringify(banners));

	fs.unlinkSync(file.filepath);

	return res.status(200).json({ success: true, banner: newBanner });
}

async function updateBanners(req, res) {
	await requireAdmin(req);
	if (!db.initialized) await db.initialize();

	const { banners } = req.body;
	if (!Array.isArray(banners)) return res.status(400).json({ error: "Date invalide." });

	await saveSetting("bannerImages", JSON.stringify(banners));

	return res.status(200).json({ success: true });
}

async function deleteBanner(req, res) {
	await requireAdmin(req);
	if (!db.initialized) await db.initialize();

	const { id } = req.query; 

	const setting = await db.Settings.findOne({ where: { name: "bannerImages" } });
	const banners = setting ? JSON.parse(setting.value || "[]") : [];

	const updated = banners.filter((b) => b.id !== id);
	await saveSetting("bannerImages", JSON.stringify(updated));

	return res.status(200).json({ success: true });
}
