const express = require("express");
const router = express.Router();
const multer = require("multer");
const authorize = require("../../../../middlewares/authorize-sapps");
const companyService = require("./company.service");

// setting storage engine
const storage = multer.diskStorage({
	destination: function (req, file, cb) {
		cb(null, "./public/data/logos/");
	},
	filename: function (req, file, cb) {
		cb(null, file.originalname);
	},
});

// initialize upload
const upload = multer({ storage: storage });

// create with file uploads
router.post(
	"/create",
	authorize(),
	upload.fields([
		{ name: "logo", maxCount: 1 },
		{ name: "navbar_logo", maxCount: 1 },
		{ name: "login_logo", maxCount: 1 },
		{ name: "loading_logo", maxCount: 1 },
		{ name: "report_logo", maxCount: 1 },
		{ name: "favicon", maxCount: 1 },
	]),
	create
);
router.post("/", authorize(), getAll);
router.post("/option", authorize(), option);
router.get("/get-by-hostname", getHostname);
router.get("/:id/delivery-trip-approver-settings", authorize(), getDeliveryTripApproverSettings);
router.get("/count", authorize(), count);

// update with file iuploads
router.put(
	"/:id",
	authorize(),
	upload.fields([
		{ name: "logo", maxCount: 1 },
		{ name: "navbar_logo", maxCount: 1 },
		{ name: "login_logo", maxCount: 1 },
		{ name: "loading_logo", maxCount: 1 },
		{ name: "report_logo", maxCount: 1 },
		{ name: "favicon", maxCount: 1 },
	]),
	update
);
router.put("/enabled/:id", authorize(), enabled);
router.delete("/:id", authorize(), _delete);

module.exports = router;

function create(req, res, next) {
	const createData = {
		...req.body,
		logo: req.files && req.files.logo ? req.files.logo[0].filename : null,
		navbar_logo: req.files && req.files.navbar_logo ? req.files.navbar_logo[0].filename : null,
		login_logo: req.files && req.files.login_logo ? req.files.login_logo[0].filename : null,
		loading_logo: req.files && req.files.loading_logo ? req.files.loading_logo[0].filename : null,
		report_logo: req.files && req.files.report_logo ? req.files.report_logo[0].filename : null,
		favicon: req.files && req.files.favicon ? req.files.favicon[0].filename : null,
	};

	companyService
		.create(createData)
		.then((result) => res.json(result))
		.catch(next);
}

function getAll(req, res, next) {
	companyService
		.getAll(req.body)
		.then((result) => res.json(result))
		.catch(next);
}

function getHostname(req, res, next) {
	companyService
		.getAll(req.query)
		.then((result) => res.json(result))
		.catch(next);
}

function getDeliveryTripApproverSettings(req, res, next) {
	companyService
		.getDeliveryTripApproverSettings(req.params.id)
		.then((result) => res.json(result))
		.catch(next);
}

function option(req, res, next) {
	// FIXED: Pass user information to service for company association validation
	// FIXED: Add validation to ensure req.user exists (should be set by authorize middleware)
	if (!req.user || !req.user.id) {
		console.error('[Companies Controller] req.user is missing or invalid:', req.user);
		return res.status(401).json({
			success: false,
			message: "User authentication required. Please login again.",
		});
	}

	// FIXED: Log for debugging in production
	if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'production') {
		console.log('[Companies Controller] option called with user.id:', req.user.id);
		console.log('[Companies Controller] req.body:', JSON.stringify(req.body));
	}

	companyService
		.option(req.body, req.user)
		.then((result) => {
			// FIXED: Log result for debugging
			if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'production') {
				console.log('[Companies Controller] option result:', JSON.stringify({
					success: result.success,
					message: result.message,
					optionsCount: result.options?.length || 0
				}));
			}
			res.json(result);
		})
		.catch((error) => {
			// FIXED: Enhanced error logging
			console.error('[Companies Controller] Error in option:', error);
			next(error);
		});
}

function count(req, res, next) {
	companyService
		.count(req.query)
		.then((result) => res.json(result))
		.catch(next);
}

function update(req, res, next) {
	const updateData = {
		...req.body,
		logo: req.files && req.files.logo ? req.files.logo[0].filename : req.body.logo ? req.body.logo : null,
		navbar_logo: req.files && req.files.navbar_logo ? req.files.navbar_logo[0].filename : req.body.navbar_logo ? req.body.navbar_logo : null,
		login_logo: req.files && req.files.login_logo ? req.files.login_logo[0].filename : req.body.login_logo ? req.body.login_logo : null,
		loading_logo: req.files && req.files.loading_logo ? req.files.loading_logo[0].filename : req.body.loading_logo ? req.body.loading_logo : null,
		report_logo: req.files && req.files.report_logo ? req.files.report_logo[0].filename : req.body.report_logo ? req.body.report_logo : null,
		favicon: req.files && req.files.favicon ? req.files.favicon[0].filename : req.body.favicon ? req.body.favicon : null,
	};

	companyService
		.update(req.params.id, updateData)
		.then((result) => res.json(result))
		.catch(next);
}

function enabled(req, res, next) {
	companyService
		.enabled(req.params.id, req.body)
		.then((result) => res.json(result))
		.catch(next);
}

function _delete(req, res, next) {
	companyService
		.delete(req.params.id)
		.then((result) => res.json(result))
		.catch(next);
}
