import { Document, Model, Types, Connection } from 'mongoose';
import { Prop, SchemaFactory, Schema } from '@nestjs/mongoose';
import { Field, ID, ObjectType } from '@nestjs/graphql';
import { Base } from '@/models/base.model';
import { Build } from '@/models/build.model';
import { BuildParts } from '@/models/build-parts.model';
import { Person } from '@/models/person.model';
import { Company } from '@/models/company.model';
import { UserType } from '@/models/user-type.model';


@ObjectType()
@Schema({ timestamps: true })
export class LivingSpaces extends Base {

    @Field(() => ID)
    readonly _id: string

    @Field(() => ID)
    @Prop({ type: Types.ObjectId, ref: Build.name, required: true })
    build: Types.ObjectId;

    @Field(() => ID, { nullable: true })
    @Prop({ type: Types.ObjectId, ref: BuildParts.name, required: false })
    part?: Types.ObjectId | null;

    @Field(() => ID)
    @Prop({ type: Types.ObjectId, ref: UserType.name, required: true })
    userType: Types.ObjectId;

    @Field(() => ID)
    @Prop({ type: Types.ObjectId, ref: Company.name, required: true })
    company: Types.ObjectId;

    @Field(() => ID)
    @Prop({ type: Types.ObjectId, ref: Person.name, required: true })
    person: Types.ObjectId;

}

export type LivingSpacesDocument = LivingSpaces & Document;
export const LivingSpacesSchema = SchemaFactory.createForClass(LivingSpaces);

export function getDynamicLivingSpaceModel(buildID: string, connection: Connection): Model<LivingSpacesDocument> {
    const collectionName = `LivingSpaces${buildID}`;
    const schema = SchemaFactory.createForClass(LivingSpaces);
    if (connection.models[collectionName]) { return connection.models[collectionName] as Model<LivingSpacesDocument> }
    return connection.model(collectionName, schema, collectionName) as unknown as Model<LivingSpacesDocument>;
}
