import { z } from "zod";
// `_id` is constructed as `ailf.user.${CurrentUser.id}` at write time. The
// account id segment is opaque (may contain `|`, `.`, etc. for SSO providers),
// so the prefix is all we constrain here. The deterministic-id invariant
// (`_id === ailf.user.${sanityUserId}`) is enforced on the write path.
const USER_ID_REGEX = /^ailf\.user\..+$/;
const TeamReferenceSchema = z.object({
    _type: z.literal("reference"),
    _ref: z.string().min(1),
    _key: z.string().optional(),
});
export const AilfUserSchema = z
    .object({
    _id: z.string().regex(USER_ID_REGEX),
    _type: z.literal("ailf.user"),
    sanityUserId: z.string().min(1),
    // Input-optional: documents created before D0075 carry only the scalar
    // `sanityUserId`. The transform below normalizes them to a single-element
    // array, so the parsed `AilfUser` always exposes a populated
    // `sanityUserIds` (the read-path migration; no document rewrite here).
    sanityUserIds: z.array(z.string().min(1)).optional(),
    email: z.string().email(),
    displayName: z.string().optional(),
    teams: z.array(TeamReferenceSchema),
    preferences: z.object({
        primaryTeam: TeamReferenceSchema.optional(),
        // No "must be one of `teams[]`" invariant (distinct from `primaryTeam`):
        // a last-used default, not declared affiliation (D0075).
        lastTeam: TeamReferenceSchema.optional(),
    }),
    updatedAt: z.string().datetime(),
})
    .transform((doc) => ({
    ...doc,
    sanityUserIds: doc.sanityUserIds && doc.sanityUserIds.length > 0
        ? doc.sanityUserIds
        : [doc.sanityUserId],
}));
