// ═══════════════════════════════════════════════════
//  lib/api/meeting-invites.ts
//
//  Client for the PUBLIC invite routes (backend @Controller('j')):
//    GET  /j/:token            → peek       (show who/what the invite is for)
//    POST /j/:token/redeem     → redeem     (passcode + name -> room code)
//    POST /j/:token/resend-otp → resendOtp  (email a fresh passcode)
//
//  Shapes below match meeting-invite.service.ts exactly.
// ═══════════════════════════════════════════════════

import { publicFetch, API_BASE_URL } from './publicFetch';

export interface InvitePeek {
  ok: boolean;
  /** true → a passcode (otp) must be entered to join */
  requires_otp: boolean;
  /** true → invite is AUTHENTICATED scope: the person must sign in to QRS */
  requires_login: boolean;
  /** true → the stored passcode aged out; offer "resend" */
  otp_expired: boolean;
  meeting: {
    room_code: string;
    title: string;
    company: string | null;
    host: string | null;
    scheduled_at: string | null;
    status: string;
    is_recorded: boolean;
  };
  recipient_name: string | null;
  expires_at: string;
}

export interface InviteRedeemResult {
  ok: boolean;
  room_code: string;
  /** AUDITOR | CLIENT | OBSERVER */
  grant_role: string;
  display_name: string;
  meeting_id: number;
  invite_id: number;
  /** short-lived guest JWT used to actually connect to the meeting socket */
  token?: string;
}

// NOTE: API_BASE_URL already ends with `/api`. If the Nest join controller is
// excluded from the global `api` prefix, drop `/api` for these three calls.
const inviteBase = () => `${API_BASE_URL}/j`;

export function peekInvite(token: string): Promise<InvitePeek> {
  return publicFetch<InvitePeek>(`${inviteBase()}/${encodeURIComponent(token)}`);
}

export function redeemInvite(
  token: string,
  body: { otp?: string; display_name?: string },
): Promise<InviteRedeemResult> {
  return publicFetch<InviteRedeemResult>(
    `${inviteBase()}/${encodeURIComponent(token)}/redeem`,
    { method: 'POST', body: JSON.stringify(body) },
  );
}

export function resendInviteOtp(
  token: string,
): Promise<{ ok: true; sent_to: string }> {
  return publicFetch(
    `${inviteBase()}/${encodeURIComponent(token)}/resend-otp`,
    { method: 'POST' },
  );
}