// Auth Delegation: ask CSM "is this email/password correct + is this user
// allowed into AOM?". CSM never mints a token here; AOM issues its own JWT.
import { csmPost, unwrap, CsmError } from './client';

export interface CsmUser {
  id: string;
  name?: string;
  email?: string;
  phone?: string;
  role?: string;
  roles?: string[];
  department?: { id?: string; name?: string; code?: string } | string;
  position?: string;
  status?: string;
}

export interface CsmVerifyResult {
  valid: boolean;
  /** Only meaningful when enforceGrant=true on CSM side. undefined = open mode. */
  access?: boolean;
  reason?: string;
  user?: CsmUser;
  webtool?: { roles?: string[]; permissions?: string[] };
}

/**
 * POST /auth/verify.
 *  - HTTP 200 { valid:true, access?, user, webtool? }  -> parsed as-is
 *  - HTTP 401 { valid:false }                          -> { valid:false } (wrong password)
 *  - 5xx / timeout                                     -> throws CsmError (caller shows "CSM unavailable")
 */
export async function verifyCsmCredentials(email: string, password: string): Promise<CsmVerifyResult> {
  try {
    const body = await csmPost('/auth/verify', { email, password });
    const data = unwrap(body) ?? {};
    return {
      valid: data?.valid === true,
      access: data?.access,
      reason: data?.reason,
      user: data?.user,
      webtool: data?.webtool,
    };
  } catch (e) {
    if (e instanceof CsmError && e.status === 401) {
      return { valid: false };
    }
    throw e;
  }
}
