import { eq, inArray } from "drizzle-orm";
import { db } from "../../core/db/client.js";
import { families, familyMembers } from "./db/schema.js";
/**
 * Implémentation du contrat cœur → module : les familles du module
 * PrivateFamily servies aux routes d'identité (register/login/me).
 */
export const privateFamilyProvider = {
    createInitialFamily(tx, userId, familyName) {
        const [family] = tx
            .insert(families)
            .values({ name: familyName, createdBy: userId })
            .returning()
            .all();
        if (!family)
            throw new Error("Échec de la création de la famille");
        tx.insert(familyMembers)
            .values({ familyId: family.id, userId, role: "admin" })
            .run();
        return family.id;
    },
    listForUser(userId) {
        const memberships = db
            .select()
            .from(familyMembers)
            .where(eq(familyMembers.userId, userId))
            .all();
        if (memberships.length === 0)
            return [];
        const familyIds = memberships.map((m) => m.familyId);
        const fams = db.select().from(families).where(inArray(families.id, familyIds)).all();
        return fams.map((f) => {
            const m = memberships.find((mm) => mm.familyId === f.id);
            return {
                id: f.id,
                name: f.name,
                createdAt: f.createdAt.toISOString(),
                role: m?.role ?? "viewer",
                permission: m?.permission ?? "full",
                reactionsEnabled: f.reactionsEnabled,
                commentsEnabled: f.commentsEnabled,
                createdBy: f.createdBy,
            };
        });
    },
};
//# sourceMappingURL=family-provider.js.map