// ─── 快速笔记后端接线层：只做数据映射，不改变原型 UI/UX ───
const QuickNoteApi = (() => {
  const API_BASE = window.AI4SALES_API_BASE || 'http://127.0.0.1:8787';
  const TENANT_ID = 'demo-tenant';
  const linkTypeToDomain = { company: 'account', person: 'contact', deal: 'deal', review: 'review' };
  const linkTypeToPrototype = { account: 'company', contact: 'person', deal: 'deal', review: 'review' };

  function localClientId(note) {
    return `prototype-${note.id}`;
  }

  function stableId(prefix, value) {
    return `${prefix}-${String(value || 'unknown').replace(/\s+/g, '-').slice(0, 80)}`;
  }

  function toDomainLink(link) {
    const type = linkTypeToDomain[link.type] || 'account';
    return {
      type,
      id: stableId(type, link.name),
      name: link.name || '未命名'
    };
  }

  function toPrototypeLink(link) {
    return {
      type: linkTypeToPrototype[link.type] || 'company',
      name: link.name
    };
  }

  function toAttachment(name, index) {
    return {
      id: stableId(`file-${index}`, name),
      name,
      contentType: 'application/octet-stream'
    };
  }

  function toDraft(note) {
    return {
      clientId: localClientId(note),
      tenantId: TENANT_ID,
      text: note.text || '',
      links: (note.links || []).map(toDomainLink),
      attachments: (note.files || []).map(toAttachment),
      occurredAt: new Date(note.ts || Date.now()).toISOString(),
      inputMode: 'typed',
      deviceId: 'ai4sales-prototype-mobile'
    };
  }

  function enrichLocal(note, quickNote, syncStatus) {
    return {
      ...note,
      quickNoteId: quickNote.id,
      quickNoteVersion: quickNote.version,
      quickNoteCandidates: quickNote.candidates || [],
      quickNoteAgentRun: quickNote.agentRun || null,
      quickNoteDerivedTasks: quickNote.derivedTasks || [],
      syncStatus
    };
  }

  function toPrototypeNote(quickNote) {
    const localId = quickNote.clientId && quickNote.clientId.startsWith('prototype-')
      ? quickNote.clientId.slice('prototype-'.length)
      : quickNote.id;
    return {
      id: localId,
      ts: Date.parse(quickNote.occurredAt || quickNote.createdAt || quickNote.updatedAt),
      text: quickNote.text,
      links: (quickNote.links || []).map(toPrototypeLink),
      files: (quickNote.attachments || []).map(attachment => attachment.name),
      quickNoteId: quickNote.id,
      quickNoteVersion: quickNote.version,
      quickNoteCandidates: quickNote.candidates || [],
      quickNoteAgentRun: quickNote.agentRun || null,
      quickNoteDerivedTasks: quickNote.derivedTasks || [],
      syncStatus: 'synced'
    };
  }

  async function request(path, options) {
    const response = await fetch(`${API_BASE}${path}`, {
      ...options,
      headers: {
        'content-type': 'application/json',
        ...(options && options.headers ? options.headers : {})
      }
    });
    const data = await response.json();
    if (!response.ok) throw new Error(data.error || `Request failed: ${response.status}`);
    return data;
  }

  async function list() {
    const data = await request(`/api/quick-notes?tenantId=${encodeURIComponent(TENANT_ID)}`);
    return (data.notes || []).map(toPrototypeNote);
  }

  async function save(note) {
    const payload = JSON.stringify(toDraft(note));
    const data = note.quickNoteId
      ? await request(`/api/quick-notes/${encodeURIComponent(note.quickNoteId)}?tenantId=${encodeURIComponent(TENANT_ID)}`, { method: 'PATCH', body: payload })
      : await request(`/api/quick-notes?tenantId=${encodeURIComponent(TENANT_ID)}`, { method: 'POST', body: payload });
    return enrichLocal(note, data.note, 'synced');
  }

  async function remove(note) {
    if (!note.quickNoteId) return;
    await request(`/api/quick-notes/${encodeURIComponent(note.quickNoteId)}?tenantId=${encodeURIComponent(TENANT_ID)}`, { method: 'DELETE' });
  }

  async function confirmFirstTask(note) {
    if (!note.quickNoteId) return null;
    const candidate = (note.quickNoteCandidates || []).find(item => item.kind === 'task' && item.status === 'pending');
    if (!candidate) return null;
    const data = await request(
      `/api/quick-notes/${encodeURIComponent(note.quickNoteId)}/candidates/${encodeURIComponent(candidate.id)}/decision?tenantId=${encodeURIComponent(TENANT_ID)}`,
      { method: 'PUT', body: JSON.stringify({ status: 'confirmed' }) }
    );
    return enrichLocal(note, data.note, 'synced');
  }

  return { list, save, remove, confirmFirstTask };
})();

Object.assign(window, { QuickNoteApi });
