import type {
  DevToolbarCategory,
  DevToolbarIssue,
  DevToolbarSeverity,
  DevToolbarSourceLocation,
} from "../types.ts";

export function createServerIssue(input: {
  ruleId: string;
  category: DevToolbarCategory;
  severity: DevToolbarSeverity;
  title: string;
  message: string;
  pathname?: string;
  source?: DevToolbarSourceLocation;
  stack?: string;
  recommendation?: string;
}): DevToolbarIssue {
  const sourceKey = input.source?.file
    ? `${input.source.file}:${input.source.line ?? 0}:${input.source.column ?? 0}`
    : "";
  return {
    id: `wrn-server-${Date.now()}-${Math.random().toString(36).slice(2)}`,
    ruleId: input.ruleId,
    category: input.category,
    severity: input.severity,
    title: input.title,
    message: input.message,
    source: input.source,
    recommendation: input.recommendation,
    fingerprint: [input.ruleId, input.pathname ?? "", sourceKey, input.message].join("|"),
    createdAt: Date.now(),
    confidence: "high",
    metadata: { pathname: input.pathname, stack: input.stack },
  };
}

export function issueFromError(
  error: unknown,
  input: {
    ruleId?: string;
    category?: DevToolbarCategory;
    title?: string;
    pathname?: string;
    source?: DevToolbarSourceLocation;
  } = {},
): DevToolbarIssue {
  const normalized = error instanceof Error ? error : new Error(String(error));
  return createServerIssue({
    ruleId: input.ruleId ?? "server/unhandled-error",
    category: input.category ?? "server",
    severity: "error",
    title: input.title ?? normalized.name ?? "Server error",
    message: normalized.message,
    pathname: input.pathname,
    source: input.source,
    stack: normalized.stack,
    recommendation: "Inspect the stack trace and open the referenced source file.",
  });
}
