import { z } from "zod";

//#region src/auth/auth-types.ts
const authMethodTypeSchema = z.enum([
	"email-password",
	"google",
	"microsoft",
	"sso"
]);
const methodOptionSchema = z.object({
	method: authMethodTypeSchema,
	providerId: z.string().optional(),
	providerType: z.enum(["oidc", "saml"]).optional(),
	displayName: z.string().optional()
});
const orgAuthInfoSchema = z.object({
	organizationId: z.string(),
	organizationName: z.string(),
	organizationSlug: z.string().optional(),
	methods: z.array(methodOptionSchema)
});
const authLookupResponseSchema = z.object({ organizations: z.array(orgAuthInfoSchema) });
const allowedAuthMethodSchema = z.discriminatedUnion("method", [
	z.object({ method: z.literal("email-password") }),
	z.object({ method: z.literal("google") }),
	z.object({ method: z.literal("microsoft") }),
	z.object({
		method: z.literal("sso"),
		providerId: z.string(),
		displayName: z.string(),
		autoProvision: z.boolean(),
		enabled: z.boolean()
	})
]);
const DEFAULT_AUTH_METHODS = [{ method: "email-password" }];
function parseAllowedAuthMethods(raw) {
	if (!raw) return DEFAULT_AUTH_METHODS;
	try {
		const parsed = JSON.parse(raw);
		if (!Array.isArray(parsed)) return DEFAULT_AUTH_METHODS;
		const valid = parsed.flatMap((item) => {
			const result = allowedAuthMethodSchema.safeParse(item);
			return result.success ? [result.data] : [];
		});
		return valid.length > 0 ? valid : DEFAULT_AUTH_METHODS;
	} catch {
		return DEFAULT_AUTH_METHODS;
	}
}
function serializeAllowedAuthMethods(methods) {
	return JSON.stringify(methods);
}

//#endregion
export { authLookupResponseSchema, authMethodTypeSchema, methodOptionSchema, orgAuthInfoSchema, parseAllowedAuthMethods, serializeAllowedAuthMethods };