/**
 * Temper auto-provisioning — calls Temper's POST /v1/onboarding/provision
 * with the super-admin token (baked into an enterprise wizard template as
 * `_temperAdmin: { url, token }` and shipped encrypted via ent:) to create
 * a per-user memory account on first onboarding.
 *
 * Org + group are get-or-create (idempotent on slug). User is non-idempotent
 * — a 409 on re-run means the user already exists; treat that as a soft skip
 * so re-running the wizard doesn't blow up.
 */

export interface ProvisionInput {
  url: string;
  adminToken: string;
  username: string;
  email: string;
  company: string;
  dept: string;
  displayName?: string;
}

export interface ProvisionResult {
  ok: true;
  user_id: string;
  username: string;
  email: string;
  display_name?: string;
  org_slug: string;
  group_slug: string;
  api_key: string;
  api_key_prefix?: string;
  default_password?: string;
  must_change_password?: boolean;
  created?: { org?: boolean; group?: boolean; user?: boolean };
}

export interface ProvisionError {
  ok: false;
  status: number;
  error: string;
  /** True when 409 — user exists; caller may treat as soft-skip. */
  conflict?: boolean;
}

export async function provisionTemperUser(input: ProvisionInput): Promise<ProvisionResult | ProvisionError> {
  const baseUrl = input.url.replace(/\/+$/, '');
  if (!baseUrl) return { ok: false, status: 0, error: 'temper url missing' };
  if (!input.adminToken) return { ok: false, status: 0, error: 'temper admin token missing' };
  if (!input.username || !input.email || !input.company || !input.dept) {
    return { ok: false, status: 0, error: 'username/email/company/dept all required' };
  }

  const body = {
    username: input.username,
    email: input.email,
    company: input.company,
    dept: input.dept,
    ...(input.displayName ? { display_name: input.displayName } : {}),
  };

  let res: Response;
  try {
    res = await fetch(`${baseUrl}/v1/onboarding/provision`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-API-Key': input.adminToken,
      },
      body: JSON.stringify(body),
    });
  } catch (e) {
    return { ok: false, status: 0, error: `network: ${(e as Error).message}` };
  }

  let parsed: any = null;
  const text = await res.text();
  try { parsed = JSON.parse(text); } catch { parsed = { raw: text }; }

  if (res.ok) {
    if (!parsed?.api_key || !parsed?.user_id) {
      return { ok: false, status: res.status, error: 'response missing api_key/user_id' };
    }
    return { ok: true, ...parsed };
  }

  return {
    ok: false,
    status: res.status,
    error: parsed?.error || parsed?.message || `HTTP ${res.status}`,
    conflict: res.status === 409,
  };
}
