import type {AccountAccess} from './account-access';
export type CustomerUser = {id:string;email:string|null;phone:string|null;name:string;username?:string;access?:AccountAccess};

export function latinDigits(value:string){
 return value.replace(/[۰-۹٠-٩]/g,char=>String('۰۱۲۳۴۵۶۷۸۹'.includes(char)?'۰۱۲۳۴۵۶۷۸۹'.indexOf(char):'٠١٢٣٤٥٦٧٨٩'.indexOf(char)));
}
export function normalizePhone(value:unknown):string|null{
 if(typeof value!=='string'||value.length>40)return null;
 let phone=latinDigits(value).trim().replace(/[\s()\-]/g,'');
 if(/^09\d{9}$/.test(phone))phone='+98'+phone.slice(1);
 else if(phone.startsWith('00'))phone='+'+phone.slice(2);
 else if(/^989\d{9}$/.test(phone))phone='+'+phone;
 return /^\+[1-9]\d{7,14}$/.test(phone)?phone:null;
}
export function normalizeEmail(value:unknown):string|null{
 if(typeof value!=='string')return null;
 const email=value.trim().toLowerCase();
 return email.length<=254&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)?email:null;
}
export function normalizeUsername(value:unknown):string|null{
 if(typeof value!=='string')return null;
 const name=value.trim().toLowerCase();
 return /^[a-z][a-z0-9_]{2,31}$/.test(name)?name:null;
}
export function loginIdentifier(value:unknown):{email:string}|{phone:string}|{username:string}|null{
 const email=normalizeEmail(value);if(email)return {email};
 const phone=normalizePhone(value);if(phone)return {phone};
 const username=normalizeUsername(value);return username?{username}:null;
}
export function validName(value:unknown):value is string{
 return typeof value==='string'&&value.trim().length>0&&value.trim().length<=80&&!/[\u0000-\u001f\u007f]/.test(value);
}
export function validPassword(value:unknown,fresh=false):value is string{
 return typeof value==='string'&&value.length>=(fresh?12:1)&&value.length<=256;
}
export function normalizeOtp(value:unknown):string|null{
 if(typeof value!=='string')return null;
 // SendOtp takes an integer: 000123 is displayed as 123. Padding is one-to-one
 // over the same million six-digit codes; it does not bypass Supabase verification.
 const code=latinDigits(value).replace(/\s/g,'');return /^\d{1,6}$/.test(code)?code.padStart(6,'0'):null;
}
