const dbSAPPS = require("../../helpers/db");
require("dotenv").config();
const { Op } = require("sequelize");

let redisClient;
try {
	// Optional: Redis may not be available in all environments
	redisClient = require("../../../../redisClient");
} catch (_) {
	redisClient = null;
}

const OPTIONS_CACHE_TTL_SECONDS = 300;
const memoryCache = new Map();

function buildOptionsCacheKey(params = {}) {
	const companyId = params.company_id ? String(params.company_id) : null;
	const companiesId = Array.isArray(params.companiesId) ? [...params.companiesId].map(String).sort().join(",") : null;
	if (companyId) return `sapps:doctypes:options:company:${companyId}`;
	if (companiesId) return `sapps:doctypes:options:companies:${companiesId}`;
	return "sapps:doctypes:options:all";
}

async function getCachedOptions(cacheKey, { allowStale = false } = {}) {
	const now = Date.now();
	const mem = memoryCache.get(cacheKey);
	if (mem && (allowStale || mem.expiresAt > now) && Array.isArray(mem.value)) {
		return { options: mem.value, source: mem.expiresAt > now ? "memory" : "memory_stale" };
	}

	if (!redisClient || typeof redisClient.get !== "function") return null;

	try {
		const cached = await redisClient.get(cacheKey);
		if (!cached) return null;
		const parsed = typeof cached === "string" ? JSON.parse(cached) : cached;
		if (!parsed) return null;
		if (!allowStale && parsed.expiresAt && Number(parsed.expiresAt) < now) return null;
		if (!Array.isArray(parsed.options)) return null;

		// refresh memory cache for faster subsequent reads
		const expiresAt = parsed.expiresAt ? Number(parsed.expiresAt) : now + OPTIONS_CACHE_TTL_SECONDS * 1000;
		memoryCache.set(cacheKey, { value: parsed.options, expiresAt });
		return { options: parsed.options, source: parsed.expiresAt && parsed.expiresAt < now ? "redis_stale" : "redis" };
	} catch (_) {
		return null;
	}
}

async function setCachedOptions(cacheKey, options) {
	if (!Array.isArray(options)) return;
	const expiresAt = Date.now() + OPTIONS_CACHE_TTL_SECONDS * 1000;
	memoryCache.set(cacheKey, { value: options, expiresAt });

	if (!redisClient || typeof redisClient.setEx !== "function") return;
	try {
		await redisClient.setEx(cacheKey, OPTIONS_CACHE_TTL_SECONDS, { options, expiresAt });
	} catch (_) {
		// ignore cache set errors
	}
}

module.exports = {
	create,
	getAll,
	option,
	count,
	update,
	enabled,
	delete: _delete,
};

/**
 * Retrieve all
 */
async function getAll(params) {
	try {
		// base filters
		const filterConditions = {};

		// company scoping (only if DocType actually has the column)
		if (dbSAPPS?.DocType?.rawAttributes?.company_id) {
			if (params.company_id) {
				filterConditions.company_id = {
					[Op.eq]: params.company_id,
				};
			} else if (params.companiesId) {
				filterConditions.company_id = {
					[Op.in]: params.companiesId,
				};
			}
		}

		if (params.doctype_id) {
			filterConditions.id = {
				[Op.eq]: params.doctype_id,
			};
		}

		// column filters
		if (params.f_name) {
			filterConditions.name = {
				[Op.iLike]: `%${params.f_name}%`,
			};
		}

		if (params.f_display_name) {
			filterConditions.display_name = {
				[Op.iLike]: `%${params.f_display_name}%`,
			};
		}

		if (params.f_modifier) {
			filterConditions["$modifier.full_name$"] = {
				[Op.iLike]: `%${params.f_modifier}%`,
			};
		}

		// global search q
		const andConditions = [];
		if (params.q) {
			andConditions.push({
				[Op.or]: [
					{ name: { [Op.iLike]: `%${params.q}%` } },
					{ display_name: { [Op.iLike]: `%${params.q}%` } },
					{ "$modifier.full_name$": { [Op.iLike]: `%${params.q}%` } },
				],
			});
		}

		const whereClause = {
			...filterConditions,
			...(andConditions.length
				? {
						[Op.and]: andConditions,
					}
				: {}),
		};

		let docTypes = [];
		docTypes = await dbSAPPS.DocType.findAll({
			where: whereClause,
			order: [["modified", "DESC"]],
			include: [
				{
					model: dbSAPPS.User,
					as: "modifier",
					attributes: ["full_name"],
				},
			],
		});

		docTypes = docTypes.map((doctype) => {
			return {
				...doctype.dataValues,
				modifier: doctype.modifier?.full_name,
			};
		});

		return {
			docTypes,
			success: true,
			message: "Loaded successfully!",
		};
	} catch (error) {
		const errorMessage = error.message || "Failed to load, please try again!";
		return {
			success: false,
			message: errorMessage,
		};
	}
}

/**
 * Get options
 */
async function option(params) {
	const cacheKey = buildOptionsCacheKey(params);
	const cachedFresh = await getCachedOptions(cacheKey);
	if (cachedFresh) {
		return {
			options: cachedFresh.options,
			success: true,
			message: "Loaded successfully!",
			cached: true,
			cacheSource: cachedFresh.source,
		};
	}

	try {
		// filter
		const filterConditions = {};

		// company scoping (only if DocType actually has the column)
		if (dbSAPPS?.DocType?.rawAttributes?.company_id) {
			if (params.company_id) {
				filterConditions.company_id = {
					[Op.eq]: params.company_id,
				};
			}

			if (params.companiesId) {
				filterConditions.company_id = {
					[Op.in]: params.companiesId,
				};
			}
		}

		// must be enabled
		filterConditions.enabled = {
			[Op.eq]: true,
		};

		let options = [];
		options = await dbSAPPS.DocType.findAll({
			where: filterConditions,
			attributes: ["id", "name", "display_name"],
			order: [["name", "ASC"]],
		});

		await setCachedOptions(cacheKey, options);

		return {
			options,
			success: true,
			message: "Loaded successfully!",
		};
	} catch (error) {
		// DB down / unstable: try stale cache as fallback
		const cachedStale = await getCachedOptions(cacheKey, { allowStale: true });
		if (cachedStale) {
			return {
				options: cachedStale.options,
				success: true,
				message: "Loaded from cache (database unavailable).",
				cached: true,
				stale: true,
				cacheSource: cachedStale.source,
			};
		}

		const errorMessage = error.message || "Failed to load, please try again!";
		return {
			success: false,
			message: errorMessage,
		};
	}
}

/**
 * Count
 */
async function count(params) {
	try {
		// filter
		const filterConditions = {};

		// must be enabled
		filterConditions.enabled = {
			[Op.eq]: true,
		};

		const count = await dbSAPPS.DocType.count({
			where: filterConditions,
		});

		return {
			count,
			success: true,
			message: "Loaded successfully!",
		};
	} catch (error) {
		const errorMessage = error.message || "Failed to load, please try again!";
		return {
			success: false,
			message: errorMessage,
		};
	}
}

/**
 * Creates a new
 */
async function create(params) {
	const transaction = await dbSAPPS.sequelize.transaction();
	try {
		// validate existing
		const existingName = await dbSAPPS.DocType.findOne({
			where: { name: params.name },
			transaction,
		});
		if (existingName) {
			return {
				success: false,
				message: `"${params.name}" is already taken.`,
			};
		}

		const existingDisplayName = await dbSAPPS.DocType.findOne({
			where: { display_name: params.display_name },
			transaction,
		});
		if (existingDisplayName) {
			return {
				success: false,
				message: `"${params.display_name}" is already taken.`,
			};
		}

		// save
		const docType = await dbSAPPS.DocType.create(params, { transaction });

		await transaction.commit();
		return {
			id: docType?.id,
			success: true,
			message: "Saved successfully!",
		};
	} catch (error) {
		await transaction.rollback();
		const errorMessage = error?.message || "Failed to save, please try again!";
		return {
			success: false,
			message: errorMessage,
		};
	}
}

/**
 * Updates an existing
 */
async function update(id, params) {
	const transaction = await dbSAPPS.sequelize.transaction();
	try {
		// validate existing
		const docType = await dbSAPPS.DocType.findByPk(id);
		if (!docType) return { success: false, message: "ID not found!" };

		// validate existing
		const existingName = await dbSAPPS.DocType.findOne({
			where: {
				name: params.name,
				id: {
					[Op.ne]: id,
				},
			},
			transaction,
		});
		if (existingName) {
			return {
				success: false,
				message: `"${params.name}" is already taken.`,
			};
		}

		const existingDisplayName = await dbSAPPS.DocType.findOne({
			where: {
				display_name: params.display_name,
				id: {
					[Op.ne]: id,
				},
			},
			transaction,
		});
		if (existingDisplayName) {
			return {
				success: false,
				message: `"${params.display_name}" is already taken.`,
			};
		}

		// save
		await docType.update(params, { transaction });

		await transaction.commit();
		return {
			success: true,
			message: "Saved successfully!",
		};
	} catch (error) {
		await transaction.rollback();
		const errorMessage = error?.message || "Failed to save, please try again!";
		return {
			success: false,
			message: errorMessage,
		};
	}
}

async function enabled(id, params) {
	const transaction = await dbSAPPS.sequelize.transaction();
	try {
		// validate existing
		const docType = await dbSAPPS.DocType.findByPk(id);
		if (!docType) return { success: false, message: "ID not found!" };

		const updateData = {};
		updateData.enabled = params.enabled;
		if (params.modified_by) updateData.modified_by = params.modified_by;
		if (params.modified) updateData.modified = params.modified;

		// save
		await docType.update(updateData, { transaction });

		await transaction.commit();
		return {
			success: true,
			message: "Saved successfully!",
		};
	} catch (error) {
		await transaction.rollback();
		const errorMessage = error?.message || "Failed to save, please try again!";
		return {
			success: false,
			message: errorMessage,
		};
	}
}

async function _delete(id) {
	const transaction = await dbSAPPS.sequelize.transaction();
	try {
		// validate existing
		const docType = await dbSAPPS.DocType.findByPk(id);
		if (!docType) return { success: false, message: "ID not found!" };

		// delete
		await docType.destroy({ transaction });

		await transaction.commit();
		return {
			success: true,
			message: "Deleted successfully!",
		};
	} catch (error) {
		await transaction.rollback();
		const errorMessage = error?.message || "Failed to delete, please try again!";
		return {
			success: false,
			message: errorMessage,
		};
	}
}
