import type { Request, Response } from "express";
import { validateFiles } from "./validateFiles";
import { validateSessionUser } from "./validateUser";
import CompanySchema from "../models/companies";
import EmployeeSchema from "../models/employees";

export type ValidateOrganizationResult = {
    files: Express.Multer.File[];
    organizationId: string;
    sessionUser: string;
};

export const validateOrganization = async (
    req: Request,
    res: Response
): Promise<ValidateOrganizationResult> => {
    const filesResul = await validateFiles(req, res);
    const { sessionUser, organizationId } = req.body;
    if (!organizationId || !sessionUser) {
        throw new Error("Faltan campos obligatorios: userId o profileId");
    }

    await validateSessionUser(sessionUser);

    const company = await CompanySchema.findOne({
        _id: organizationId,
    });

    if (!company) {
        throw new Error("No se ha encontrado la organización");
    }

    const employee = await EmployeeSchema.findOne({
        userId: sessionUser,
        companyId: organizationId,
    });

    if (!employee) {
        throw new Error("El usuario no pertenece a la organización");
    }

    return {
        files: filesResul.files,
        organizationId,
        sessionUser,
    };
};
