import { Op } from 'sequelize';
import db from '../database/models/index.js';

const ROLE_CODE_PREFIX: Record<string, string> = {
    ASM: 'ASM',
    RBM: 'RBM',
    RM: 'RBM',
    'DD-ZM': 'ZM',
    ZM: 'ZM',
    ZBH: 'ZBH',
    'DD Lead': 'DDL'
};

const normalizeCode = (value: string) =>
    value
        .trim()
        .toUpperCase()
        .replace(/\s+/g, '-');

const shouldGenerateCode = (roleCode?: string | null) => {
    if (!roleCode) return false;
    return Boolean(ROLE_CODE_PREFIX[roleCode]);
};

export const resolveManagerCode = async (
    roleId: string,
    roleCode?: string | null,
    providedCode?: string | null
): Promise<string | null> => {
    const normalizedProvided = providedCode ? normalizeCode(providedCode) : null;
    if (normalizedProvided) return normalizedProvided;
    if (!shouldGenerateCode(roleCode)) return null;

    const prefix = ROLE_CODE_PREFIX[roleCode as string];
    const rows = await db.UserRole.findAll({
        where: {
            roleId,
            managerCode: { [Op.iLike]: `${prefix}-%` }
        },
        attributes: ['managerCode']
    });

    let maxSeq = 0;
    for (const row of rows as any[]) {
        const code = String(row.managerCode || '');
        const parts = code.split('-');
        const seq = Number(parts[parts.length - 1]);
        if (Number.isFinite(seq) && seq > maxSeq) maxSeq = seq;
    }

    return `${prefix}-${String(maxSeq + 1).padStart(3, '0')}`;
};
