import { z } from 'zod';
import { Types } from 'mongoose';
import { OrganizationModel } from './mongoose-models/OrganizationModel.js';
import { UserModel } from './mongoose-models/UsersModel.js';
export const getUserId = (userEmail) => UserModel.findOne({ email: userEmail }).lean();
export const userEmailInputParser = z.object({
    userEmail: z.string(),
});
const orgNameInputParser = z.object({
    name: z.string(),
});
export const orgIdInputParser = z.object({
    orgId: z.string(),
});
export const insertOrganizationInputParser = z.object({
    ...orgNameInputParser.shape,
    ...userEmailInputParser.shape,
});
export const updateOrganizationNameInputParser = z.object({
    ...orgIdInputParser.shape,
    ...userEmailInputParser.shape,
    newName: z.string(),
});
export const createOrganization = async ({ name, userEmail, }) => {
    const user = await getUserId(userEmail);
    if (!user)
        return null;
    return OrganizationModel.create({
        name,
        createdBy: user._id,
        users: [user._id],
    });
};
export const getOrganizationsForUser = async ({ userEmail, }) => {
    const user = await getUserId(userEmail);
    return OrganizationModel.find({ users: user._id }).lean();
};
export const updateOrganizationName = async ({ orgId, newName, userEmail, }) => {
    const user = await getUserId(userEmail);
    return OrganizationModel.findOneAndUpdate({
        _id: new Types.ObjectId(orgId),
        createdBy: user._id,
    }, { name: newName }, { new: true }).lean();
};
export const getCurrentOrganizationDetails = async ({ orgId, }) => {
    var _a;
    const organization = await OrganizationModel.findOne({
        _id: new Types.ObjectId(orgId),
    }).lean();
    if (!organization)
        return null;
    const users = (await UserModel.find({ _id: { $in: organization.users } }, { _id: 1, email: 1 }).lean());
    const usersWithEmail = users.map(user => {
        return {
            id: user._id.toString(),
            email: user.email,
        };
    });
    return {
        id: organization._id.toString(),
        name: organization.name,
        createdBy: {
            id: organization.createdBy.toString(),
            email: (_a = usersWithEmail.find(user => user.id === organization.createdBy.toString())) === null || _a === void 0 ? void 0 : _a.email,
        },
        users: usersWithEmail,
    };
};
