import { Some, None, Ok, Err, type Option, type Result } from "@tsus/runtime";export type Profile = { name: string; email: Option<string>; phone: Option<string> };export type ProfilePatch = { name: Option<string>; email: Option<Option<string>>; phone: Option<Option<string>>;};export type ProfileError = { kind: "invalid_name" | "invalid_email" | "invalid_phone" };const validName = (s: string): boolean => s !== "";const validEmail = (s: string): boolean => { const parts = s.split("@"); return parts.length === 2 && parts[0] !== "" && parts[1] !== "";};const validPhone = (s: string): boolean => { const digits = s.replace(/[^0-9]/g, "").length; return /^\+?[0-9 -]*$/.test(s) && digits >= 7 && digits <= 15;};const checked = (raw: string, valid: (s: string) => boolean, kind: ProfileError["kind"]): Result<string, ProfileError> => { const t = raw.trim(); return valid(t) ? Ok(t) : Err({ kind });};const setOrClear = (next: Option<string>, valid: (s: string) => boolean, kind: ProfileError["kind"]): Result<Option<string>, ProfileError> => match (next) { None => Ok(None), Some(raw) => checked(raw, valid, kind).map((s) => Some(s)), };const nextField = ( current: Option<string>, change: Option<Option<string>>, valid: (s: string) => boolean, kind: ProfileError["kind"],): Result<Option<string>, ProfileError> => match (change) { None => Ok(current), Some(next) => setOrClear(next, valid, kind), };const nextName = (current: string, change: Option<string>): Result<string, ProfileError> => match (change) { None => Ok(current), Some(raw) => checked(raw, validName, "invalid_name"), };export const applyPatch = (profile: Profile, patch: ProfilePatch): Result<Profile, ProfileError> => nextName(profile.name, patch.name).andThen((name) => nextField(profile.email, patch.email, validEmail, "invalid_email").andThen((email) => nextField(profile.phone, patch.phone, validPhone, "invalid_phone").map((phone) => ({ name, email, phone })), ), );