/**
 * Types for @bytelyst/auth-client.
 * Browser/React Native-safe — no Node.js dependencies.
 */

export interface AuthClientConfig {
  /** Platform-service base URL (e.g. "http://localhost:4003/api" or "https://api.example.com"). */
  baseUrl: string;

  /** Product identifier sent with every request as x-product-id header. */
  productId: string;

  /** Storage adapter for tokens. Defaults to localStorage if available. */
  storage?: TokenStorage;

  /** Optional prefix for storage keys. Default: product ID. */
  storagePrefix?: string;

  /** Request timeout in milliseconds. Default: 15000. */
  timeoutMs?: number;
}

export interface TokenStorage {
  getItem(key: string): string | null;
  setItem(key: string, value: string): void;
  removeItem(key: string): void;
}

export interface AuthUser {
  id: string;
  email: string;
  displayName: string;
  role: string;
  plan: string;
  mfaEnabled?: boolean;
  mfaMethods?: string[];
  providers?: string[];
  products?: string[];
}

export interface AuthResult {
  accessToken: string;
  refreshToken: string;
  user: AuthUser;
}

export interface MfaRequiredResult {
  mfaRequired: true;
  mfaChallenge: string;
  methods: string[];
}

export interface TotpSetupResult {
  secret: string;
  otpauthUri: string;
  recoveryCodes: string[];
}

export interface MfaStatus {
  mfaEnabled: boolean;
  methods: string[];
  recoveryCodesRemaining: number;
}

export interface AuthProvider {
  provider: string;
  email: string;
  linkedAt: string;
  lastUsedAt: string | null;
}

export interface Passkey {
  credentialId: string;
  friendlyName: string;
  deviceType: string;
  backedUp: boolean;
  lastUsedAt: string;
  createdAt: string;
}

export interface Device {
  fingerprint: string;
  trustLevel: 'trusted' | 'remembered' | 'unknown';
  deviceInfo: Record<string, string | undefined>;
  lastIp?: string;
  lastLocation?: string;
  trustExpiresAt: string;
  createdAt: string;
  lastSeenAt: string;
  isTrusted: boolean;
}

export interface LoginEventInfo {
  id: string;
  result: string;
  method: string;
  ip: string;
  userAgent?: string;
  fingerprint?: string;
  location?: string;
  riskLevel: string;
  riskScore: number;
  riskFlags: string[];
  createdAt: string;
}

export interface SecurityOverview {
  totalUsers: number;
  mfaAdoptionPercent: number;
  providerDistribution: Record<string, number>;
  activeSessions: number;
  suspiciousEvents24h: number;
}

export interface AuthClient {
  // ── Token management ────────────────────────────
  getAccessToken(): string | null;
  getRefreshToken(): string | null;
  setTokens(accessToken: string, refreshToken: string): void;
  clearTokens(): void;
  isAuthenticated(): boolean;

  // ── Auth operations ─────────────────────────────
  login(email: string, password: string): Promise<AuthResult | MfaRequiredResult>;
  register(email: string, password: string, displayName: string): Promise<AuthResult>;
  getMe(): Promise<AuthUser>;
  refreshAccessToken(): Promise<boolean>;

  // ── OAuth / Social login ────────────────────────
  loginWithGoogle(idToken: string): Promise<AuthResult | MfaRequiredResult>;
  loginWithMicrosoft(idToken: string): Promise<AuthResult | MfaRequiredResult>;
  loginWithApple(idToken: string): Promise<AuthResult | MfaRequiredResult>;

  // ── Provider management ─────────────────────────
  getProviders(): Promise<AuthProvider[]>;
  linkProvider(provider: string, idToken: string): Promise<void>;
  unlinkProvider(provider: string): Promise<void>;

  // ── MFA ─────────────────────────────────────────
  verifyMfa(challengeToken: string, code: string, method: 'totp' | 'recovery'): Promise<AuthResult>;
  setupTotp(): Promise<TotpSetupResult>;
  verifyTotpSetup(code: string): Promise<void>;
  disableMfa(code: string): Promise<void>;
  getMfaStatus(): Promise<MfaStatus>;
  regenerateRecoveryCodes(): Promise<{ codes: string[] }>;

  // ── Passkeys (WebAuthn) ─────────────────────────
  getPasskeyRegisterOptions(): Promise<unknown>;
  verifyPasskeyRegistration(response: unknown): Promise<void>;
  getPasskeyAuthOptions(): Promise<unknown>;
  verifyPasskeyAuth(response: unknown): Promise<AuthResult>;
  listPasskeys(): Promise<Passkey[]>;
  deletePasskey(id: string): Promise<void>;

  // ── Devices ─────────────────────────────────────
  listDevices(): Promise<Device[]>;
  trustDevice(
    fingerprint: string,
    trustLevel: 'trusted' | 'remembered',
    deviceInfo?: Record<string, string>
  ): Promise<void>;
  revokeDevice(fingerprint: string): Promise<void>;
  revokeAllDevices(): Promise<void>;

  // ── Step-up auth ────────────────────────────────
  stepUp(method: string, credential: string): Promise<{ stepUpToken: string }>;

  // ── Login history ───────────────────────────────
  getLoginHistory(limit?: number): Promise<LoginEventInfo[]>;

  // ── Admin security ──────────────────────────────
  getSecurityOverview(): Promise<SecurityOverview>;
  unlockUser(userId: string): Promise<void>;
  getAdminLoginEvents(opts?: { suspicious?: boolean; limit?: number }): Promise<LoginEventInfo[]>;
  getAdminDevices(userId: string): Promise<Device[]>;
  exportAuthData(): Promise<unknown>;

  // ── Password management ─────────────────────────
  forgotPassword(email: string): Promise<{ message: string }>;
  resetPassword(token: string, newPassword: string): Promise<{ message: string }>;
  changePassword(currentPassword: string, newPassword: string): Promise<{ message: string }>;

  // ── Account management ──────────────────────────
  deleteAccount(password: string): Promise<{ message: string }>;
  cancelDeletion(): Promise<{ message: string }>;

  // ── Email verification ──────────────────────────
  verifyEmail(token: string): Promise<{ message: string }>;
  resendVerification(email: string): Promise<{ message: string }>;
}
