// PLACE AT: lib/api/meeting.api.ts
// REST helper for the /meetings backend. Matches your other lib/api modules.

const API_BASE = process.env.NEXT_PUBLIC_API_URL || "";

export interface MeetingTokenSource { getToken: () => string; }

function headers(getToken: () => string): HeadersInit {
  return { "Content-Type": "application/json", Authorization: `Bearer ${getToken()}` };
}
async function unwrap<T = any>(res: Response): Promise<T> {
  if (!res.ok) {
    let msg = `Request failed (${res.status})`;
    try { const b = await res.json(); msg = b?.message || msg; } catch { /* noop */ }
    throw new Error(msg);
  }
  return res.json();
}

export function makeMeetingApi(src: MeetingTokenSource) {
  const H = () => headers(src.getToken);
  return {
    createMeeting: (body: { title: string; description?: string; scheduledAt?: string }) =>
      fetch(`${API_BASE}/meetings`, { method: "POST", headers: H(), body: JSON.stringify(body) }).then(unwrap),
    createForAudit: (auditRowId: number, body?: { title?: string }) =>
      fetch(`${API_BASE}/meetings/for-audit/${auditRowId}`, { method: "POST", headers: H(), body: JSON.stringify(body || {}) }).then(unwrap),
    listMeetings: () => fetch(`${API_BASE}/meetings`, { headers: H() }).then(unwrap),
    getMeeting: (id: number) => fetch(`${API_BASE}/meetings/${id}`, { headers: H() }).then(unwrap),
    getByCode: (roomCode: string) => fetch(`${API_BASE}/meetings/by-code/${roomCode}`, { headers: H() }).then(unwrap),
    endMeeting: (id: number) => fetch(`${API_BASE}/meetings/${id}/end`, { method: "POST", headers: H() }).then(unwrap),
    cancelMeeting: (id: number) => fetch(`${API_BASE}/meetings/${id}/cancel`, { method: "POST", headers: H() }).then(unwrap),
    createInvite: (id: number, body: { email: string; name?: string; role?: string }) =>
      fetch(`${API_BASE}/meetings/${id}/invites`, { method: "POST", headers: H(), body: JSON.stringify(body) }).then(unwrap),
    sendInvite: (inviteId: number) =>
      fetch(`${API_BASE}/meetings/invites/${inviteId}/send`, { method: "POST", headers: H() }).then(unwrap),
    listInvites: (id: number) => fetch(`${API_BASE}/meetings/${id}/invites`, { headers: H() }).then(unwrap),
    getTurnCredentials: async (): Promise<RTCIceServer[]> => {
      try {
        const r = await fetch(`${API_BASE}/meetings/turn-credentials`, { headers: H() });
        if (!r.ok) throw new Error();
        const data = await r.json();
        return data.iceServers || [{ urls: "stun:stun.l.google.com:19302" }];
      } catch { return [{ urls: "stun:stun.l.google.com:19302" }]; }
    },
  };
}
