import type { ScheduledConditionItem, WorkbenchAlert } from "../types";

const SCHEDULED_CONDITION_ALERT_ID_PREFIX = "scheduled-condition-alert-";

export function createScheduledConditionAlerts(
  conditions: ScheduledConditionItem[]
): WorkbenchAlert[] {
  return conditions
    .filter(isAlertCondition)
    .sort((a, b) => getScheduledConditionTimestamp(b) - getScheduledConditionTimestamp(a))
    .map((condition) => ({
      id: `${SCHEDULED_CONDITION_ALERT_ID_PREFIX}${condition.id}`,
      title: `待复核：${condition.title}`,
      description: condition.detail ?? condition.summary,
      time: formatScheduledConditionTime(condition.scheduledAt)
    }));
}

export function getScheduledConditionIdFromAlertId(alertId: string) {
  if (!alertId.startsWith(SCHEDULED_CONDITION_ALERT_ID_PREFIX)) return null;
  return alertId.slice(SCHEDULED_CONDITION_ALERT_ID_PREFIX.length);
}

function isAlertCondition(condition: ScheduledConditionItem) {
  return condition.kind === "condition" && condition.status === "error";
}

function getScheduledConditionTimestamp(condition: ScheduledConditionItem) {
  const scheduledAt = Date.parse(condition.scheduledAt);
  return Number.isNaN(scheduledAt) ? condition.updatedAt : scheduledAt;
}

function formatScheduledConditionTime(value: string) {
  const match = value.match(/T(\d{2}:\d{2})/);
  return match?.[1] ?? value;
}
