import { api } from './http';

export interface MemberMe {
  tenant_id: string;
  uid: string;
  origin: string;
  zitadel_email?: string;
  display_name?: string;
  avatar?: string;
  phone?: string;
  language?: string;
  currency?: string;
  status: string;
  business_email?: string;
  business_email_verified: boolean;
  business_phone?: string;
  business_phone_verified: boolean;
  totp_enrolled: boolean;
}

export interface VerificationStart {
  challenge_id: string;
  expires_in: number;
}

export interface TOTPStatus {
  enrolled: boolean;
  backup_codes_remaining: number;
}

export interface TOTPEnrollStart {
  otpauth_url: string;
  issuer: string;
  account: string;
}

export function getMe() {
  return api<MemberMe>('/api/v1/members/me');
}

export function updateMe(body: {
  display_name?: string;
  language?: string;
  currency?: string;
  phone?: string;
}) {
  return api<MemberMe>('/api/v1/members/me', {
    method: 'PATCH',
    body: JSON.stringify(body),
  });
}

export function startEmailVerification(target: string) {
  return api<VerificationStart>('/api/v1/members/me/verifications/email/start', {
    method: 'POST',
    body: JSON.stringify({ target }),
  });
}

export function confirmEmailVerification(challengeId: string, code: string) {
  return api('/api/v1/members/me/verifications/email/confirm', {
    method: 'POST',
    body: JSON.stringify({ challenge_id: challengeId, code }),
  });
}

export function startPhoneVerification(target: string) {
  return api<VerificationStart>('/api/v1/members/me/verifications/phone/start', {
    method: 'POST',
    body: JSON.stringify({ target }),
  });
}

export function confirmPhoneVerification(challengeId: string, code: string) {
  return api('/api/v1/members/me/verifications/phone/confirm', {
    method: 'POST',
    body: JSON.stringify({ challenge_id: challengeId, code }),
  });
}

export function getTOTPStatus() {
  return api<TOTPStatus>('/api/v1/members/me/totp');
}

export function startTOTPEnroll() {
  return api<TOTPEnrollStart>('/api/v1/members/me/totp/enroll-start', {
    method: 'POST',
    body: '{}',
  });
}

export function confirmTOTPEnroll(code: string) {
  return api<{ backup_codes: string[] }>(
    '/api/v1/members/me/totp/enroll-confirm',
    { method: 'POST', body: JSON.stringify({ code }) },
  );
}

export function disableTOTP() {
  return api('/api/v1/members/me/totp', { method: 'DELETE' });
}

export interface TOTPVerifyResult {
  step_up_token: string;
  expires_in: number;
}

export function verifyTOTP(code: string, purpose = 'change_password') {
  return api<TOTPVerifyResult>('/api/v1/members/me/totp/verify', {
    method: 'POST',
    body: JSON.stringify({ code, purpose }),
  });
}

/** 從 verify 回應取出 step-up token（相容舊版 envelope 誤解析） */
export function pickStepUpToken(
  res: TOTPVerifyResult | Record<string, unknown>,
): string {
  const token =
    (res as TOTPVerifyResult).step_up_token ??
    (res as { stepUpToken?: string }).stepUpToken;
  return typeof token === 'string' ? token.trim() : '';
}

export function changePassword(
  currentPassword: string,
  newPassword: string,
  opts?: { stepUpToken?: string; totpCode?: string },
) {
  const body: Record<string, string> = {
    current_password: currentPassword,
    new_password: newPassword,
  };
  if (opts?.stepUpToken) body.step_up_token = opts.stepUpToken;
  if (opts?.totpCode) body.totp_code = opts.totpCode.replace(/\s/g, '');
  return api<{ ok: boolean }>('/api/v1/members/me/password', {
    method: 'POST',
    body: JSON.stringify(body),
  });
}
