import mongoose, { Schema, Model, Document } from 'mongoose';
import { IPerson } from './People';
import { IBuildPartsInterface } from './BuildParts';
import { ICompanyInterface } from './Company';
import { Base } from './base';
import { IUserType } from './UserTypes';
import { randomUUID } from 'crypto';

interface ILivingSpaces extends Base, Document {
    part: mongoose.Types.ObjectId | IBuildPartsInterface;
    company: mongoose.Types.ObjectId | ICompanyInterface;
    person: mongoose.Types.ObjectId | IPerson;
    userType: mongoose.Types.ObjectId | IUserType;
}

function getDynamicLivingSpaceModel(collectionToken: string): Model<ILivingSpaces> {
    const collectionName = `LivingSpaces${collectionToken}`;
    if (mongoose.models[collectionName]) { return mongoose.models[collectionName] as Model<ILivingSpaces> }
    const LivingSpacesSchema = new Schema<ILivingSpaces>({
        uuid: { type: String, required: false, unique: true, default: () => randomUUID() },
        part: { type: Schema.Types.ObjectId, ref: "BuildParts", required: true },
        company: { type: Schema.Types.ObjectId, ref: "Company", required: true },
        person: { type: Schema.Types.ObjectId, ref: "Person", required: true },
        userType: { type: Schema.Types.ObjectId, ref: "UserType", required: true },
        expiryStarts: { type: Date, required: false, default: new Date() },
        expiryEnds: { type: Date, required: false, default: new Date("2900-01-01T03:00:00+03:00") },
        isConfirmed: { type: Boolean, required: false, default: false },
        deleted: { type: Boolean, required: false, default: false },
        active: { type: Boolean, required: false, default: true },
        crypUuId: { type: String, required: false },
        createdCredentialsToken: { type: String, required: false },
        updatedCredentialsToken: { type: String, required: false },
        confirmedCredentialsToken: { type: String, required: false },
        isNotificationSend: { type: Boolean, required: false, default: false },
        isEmailSend: { type: Boolean, required: false, default: false },
        refInt: { type: Number, required: false, default: 0 },
        refId: { type: String, required: false },
        replicationId: { type: Number, required: false, default: 0 },
    }, { timestamps: true });
    return mongoose.model<ILivingSpaces>(collectionName, LivingSpacesSchema, collectionName);
}

export { getDynamicLivingSpaceModel };
export type { ILivingSpaces };
