import { Document, Model, Types, Connection, connection as defaultConnection } from 'mongoose';
import { randomUUID } from 'crypto';
import { Prop, SchemaFactory } from '@nestjs/mongoose';
import { Field, ID, ObjectType } from '@nestjs/graphql';
import { Base } from '@/models/base.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()
export class LivingSpaces extends Base {
    @Field(() => ID)
    @Prop({ type: Types.ObjectId, ref: BuildParts.name, required: true })
    part: 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;

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


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

export function getDynamicLivingSpaceModel(collectionToken: string, conn?: Connection): Model<LivingSpacesDocument> {
    const connection = conn || defaultConnection;
    const collectionName = `LivingSpaces${collectionToken}`;
    if (connection.models[collectionName]) { return connection.models[collectionName] as Model<LivingSpacesDocument> }
    const schema = SchemaFactory.createForClass(LivingSpaces);
    schema.add({ uuid: { type: String, required: false, unique: true, default: () => randomUUID() } });
    return connection.model(collectionName, schema, collectionName) as unknown as Model<LivingSpacesDocument>;
}
