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

/**
 * Generate unique incident code with format: SCYYYYMMdd-XXXX
 * Example: SC20260515-0001, SC20260515-0002, etc.
 *
 * @returns Promise<string> Generated incident code
 */
export async function generateIncidentCode(): Promise<string> {
	try {
		// Format: SCYYYYMMdd
		const today = new Date();
		const year = today.getFullYear();
		const month = String(today.getMonth() + 1).padStart(2, '0');
		const day = String(today.getDate()).padStart(2, '0');
		const datePrefix = `SC${year}${month}${day}`;

		// Get the highest sequence number for today's date
		const query = `
			SELECT 
				COALESCE(
					MAX(
						CAST(
							SUBSTRING(code, LENGTH(:datePrefix) + 2) AS INTEGER
						)
					),
					0
				) as max_sequence
			FROM incidents
			WHERE code LIKE :codePattern
				AND deleted_at IS NULL
		`;

		const result = (await sequelize.query(query, {
			replacements: {
				datePrefix: datePrefix,
				codePattern: `${datePrefix}-%`,
			},
			type: QueryTypes.SELECT,
		})) as any[];

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

		return `${datePrefix}-${sequenceStr}`;
	} catch (error) {
		console.error('Error generating incident code:', error);
		throw error;
	}
}

/**
 * Validate incident code format
 * Format: SCYYYYMMdd-XXXX
 *
 * @param code Code to validate
 * @returns boolean True if valid format
 */
export function validateIncidentCode(code: string): boolean {
	const pattern = /^SC\d{8}-\d{4}$/;
	return pattern.test(code);
}

/**
 * Parse incident code to extract date and sequence
 *
 * @param code Incident code to parse
 * @returns Object with year, month, day, sequence
 */
export function parseIncidentCode(code: string) {
	if (!validateIncidentCode(code)) {
		throw new Error('Invalid incident code format');
	}

	const yearStr = code.substring(3, 7);
	const monthStr = code.substring(7, 9);
	const dayStr = code.substring(9, 11);
	const sequenceStr = code.substring(12, 16);

	return {
		year: parseInt(yearStr, 10),
		month: parseInt(monthStr, 10),
		day: parseInt(dayStr, 10),
		sequence: parseInt(sequenceStr, 10),
	};
}
