import { effectiveElapsedMs } from './slaBusinessTime.js';

export type SlaBucket = 'healthy' | 'warning' | 'critical' | 'breached';

export function getTatInMs(value: number, unit: string): number {
    let factor = unit === 'days' ? 24 * 60 * 60 * 1000 : 60 * 60 * 1000;
    if (process.env.DEBUG_SLA_FAST_MODE === 'true') {
        factor = factor / 60;
    }
    return value * factor;
}

export function bucketFromPercent(percent: number, isBreached: boolean): SlaBucket {
    if (isBreached || percent >= 100) return 'breached';
    if (percent >= 76) return 'critical';
    if (percent >= 26) return 'warning';
    return 'healthy';
}

export function formatSlaDuration(ms: number): string {
    const abs = Math.abs(ms);
    const mins = Math.floor(abs / 60000);
    if (mins < 60) return `${mins}m`;
    const hours = Math.floor(mins / 60);
    if (hours < 48) return `${hours}h`;
    const days = Math.floor(hours / 24);
    return `${days}d`;
}

export function ownerRoleMatchesUser(ownerRole: string, userRoleCode: string | undefined | null): boolean {
    if (!ownerRole || !userRoleCode) return false;
    const userNorm = userRoleCode.replace(/_/g, '-').toUpperCase();
    return ownerRole.split(',').some((part) => {
        const p = part.trim().replace(/\s+/g, '-').toUpperCase();
        return p === userNorm || userNorm.includes(p) || p.includes(userNorm);
    });
}

export function computeSlaTrackView(
    track: { startTime: Date | string; isBreached?: boolean; metadata?: Record<string, unknown> | null },
    config: { tatHours: number; tatUnit: string },
    now = Date.now()
) {
    const startMs = new Date(track.startTime).getTime();
    const tatMs = getTatInMs(config.tatHours, config.tatUnit);
    const elapsedMs = effectiveElapsedMs(track, now);
    const deadline = new Date(startMs + tatMs);
    const percentUsed = tatMs > 0 ? Math.round((elapsedMs / tatMs) * 100) : 0;
    const isBreached = Boolean(track.isBreached) || elapsedMs >= tatMs;
    const bucket = bucketFromPercent(percentUsed, isBreached);
    const msRemaining = tatMs - elapsedMs;
    const meta = track.metadata || {};
    const isPaused = Boolean(meta.pausedAt);

    return {
        deadline,
        percentUsed,
        bucket,
        isBreached,
        isPaused,
        remainingLabel: isPaused
            ? 'Paused'
            : msRemaining > 0
              ? `${formatSlaDuration(msRemaining)} left`
              : `${formatSlaDuration(-msRemaining)} overdue`
    };
}
