export type AccountAccess = {
 user_id:string; status:'active'|'suspended'|'closed'; trading_enabled:boolean;
 withdrawals_enabled:boolean; version:number; reason:string; updated_at:string|null;
};
export type AccountCapability='login'|'trading'|'withdrawal';
export const ACCESS_POLL_INTERVAL=3000;
export function parseAccountAccess(value:unknown,expectedUser?:string):AccountAccess|null{
 if(!value||typeof value!=='object'||Array.isArray(value))return null;
 const a=value as Record<string,unknown>;
 if(typeof a.user_id!=='string'||!a.user_id||expectedUser&&a.user_id!==expectedUser||!['active','suspended','closed'].includes(String(a.status))||typeof a.trading_enabled!=='boolean'||typeof a.withdrawals_enabled!=='boolean'||!Number.isSafeInteger(a.version)||Number(a.version)<0||!(a.reason===null||typeof a.reason==='string')||!(a.updated_at===null||typeof a.updated_at==='string'))return null;
 return {user_id:a.user_id,status:a.status as AccountAccess['status'],trading_enabled:a.trading_enabled,withdrawals_enabled:a.withdrawals_enabled,version:Number(a.version),reason:typeof a.reason==='string'?a.reason:'',updated_at:a.updated_at as string|null};
}
export function accessRestriction(access:AccountAccess|null|undefined,capability:AccountCapability='login'){
 if(!access)return 'وضعیت دسترسی حساب در دسترس نیست. کمی بعد دوباره تلاش کنید.';
 if(access.status==='suspended')return 'حساب شما تعلیق شده و ورود موقتاً غیرفعال است. برای پیگیری با پشتیبانی تماس بگیرید.';
 if(access.status==='closed')return 'حساب شما بسته شده و امکان ورود ندارد. اطلاعات و سوابق حساب محفوظ است؛ برای پیگیری با پشتیبانی تماس بگیرید.';
 if(capability==='trading'&&!access.trading_enabled)return 'امکان معامله برای حساب شما غیرفعال شده است. موجودی و سوابق شما همچنان قابل مشاهده است.';
 if(capability==='withdrawal'&&!access.withdrawals_enabled)return 'امکان برداشت برای حساب شما غیرفعال شده است. موجودی و سوابق شما همچنان قابل مشاهده است.';
 return '';
}
export function acceptAccessSnapshot(current:AccountAccess|null,next:AccountAccess,userId:string){
 return next.user_id===userId&&(!current||current.user_id!==userId||next.version>=current.version);
}

export type AccountAccessSummary=Pick<AccountAccess,'status'|'trading_enabled'|'withdrawals_enabled'|'version'>;
export function accountStatusLabel(status:AccountAccess['status'],locale='fa'){
 const labels={fa:{active:'فعال',suspended:'تعلیق کاربر',closed:'حساب بسته'},en:{active:'Active',suspended:'Account suspended',closed:'Account closed'},ar:{active:'نشط',suspended:'الحساب معلّق',closed:'الحساب مغلق'}};
 return labels[locale==='en'?'en':locale==='ar'?'ar':'fa'][status];
}
