import sequelize from '#services/database/sequelize/sequelizeService';
import { QueryTypes } from 'sequelize';

/**
 * Tự động tạo code theo dạng MTB-01, MTB-02, MTB-03, ...
 * MTB = Mẫu Thông Báo
 *
 * Ví dụ: MTB-01, MTB-02, ..., MTB-09, MTB-10, MTB-99, MTB-100
 *
 * @returns Promise<string> Generated template code
 */
export async function generateTemplateCode(): Promise<string> {
	const query = `
		SELECT
			COALESCE(
				MAX(
					CAST(
						SUBSTRING(code, LENGTH('MTB-') + 1) AS INTEGER
					)
				),
				0
			) as max_sequence
		FROM notification_templates
		WHERE code ~ '^MTB-[0-9]+$'
	`;

	const result = (await sequelize.query(query, {
		type: QueryTypes.SELECT,
	})) as any[];

	const maxSequence = result[0]?.max_sequence || 0;
	const nextSequence = maxSequence + 1;
	const sequenceStr = String(nextSequence).padStart(2, '0');

	return `MTB-${sequenceStr}`;
}
