export async function syncToAtlassian(
  cfg: { siteUrl: string; email: string; apiToken: string; projectKey: string; issueType: string },
  fields: { title: string; description: string; priority?: string },
): Promise<{ external_id: string; external_url: string | null }> {
  const base = cfg.siteUrl.replace(/\/$/, '');
  const auth = Buffer.from(`${cfg.email}:${cfg.apiToken}`).toString('base64');
  const priorityName =
    fields.priority === 'high' ? 'High' : fields.priority === 'low' ? 'Low' : 'Medium';

  const body = {
    fields: {
      project: { key: cfg.projectKey },
      summary: fields.title.slice(0, 250),
      description: {
        type: 'doc',
        version: 1,
        content: [
          {
            type: 'paragraph',
            content: [{ type: 'text', text: fields.description.slice(0, 3000) }],
          },
        ],
      },
      issuetype: { name: cfg.issueType || 'Task' },
      priority: { name: priorityName },
    },
  };

  const res = await fetch(`${base}/rest/api/3/issue`, {
    method: 'POST',
    headers: {
      Authorization: `Basic ${auth}`,
      Accept: 'application/json',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(body),
  });
  if (!res.ok) throw new Error(`Atlassian HTTP ${res.status}: ${(await res.text()).slice(0, 240)}`);
  const issue = await res.json() as { id: string; key: string; self?: string };
  return {
    external_id: issue.key || issue.id,
    external_url: `${base}/browse/${issue.key}`,
  };
}
