import { Injectable } from '@nestjs/common';
import { CreateUserTypesInput } from './dto/create-user-types.input';
import { InjectModel } from '@nestjs/mongoose';
import { Types, Model } from 'mongoose';
import { UserType, UserTypeDocument } from '@/models/user-type.model';

@Injectable()
export class UserTypesService {

    constructor(
        @InjectModel(UserType.name) private readonly userTypesModel: Model<UserTypeDocument>
    ) { }

    async findAll(projection?: any): Promise<UserTypeDocument[]> {
        return this.userTypesModel.find({}, projection, { lean: false }).populate({ path: 'person', select: projection?.person }).exec();
    }

    async findById(id: Types.ObjectId, projection?: any): Promise<UserTypeDocument | null> {
        return this.userTypesModel.findById(id, projection, { lean: false }).populate({ path: 'person', select: projection?.person }).exec();
    }

    async create(input: CreateUserTypesInput): Promise<UserTypeDocument> {
        const user = new this.userTypesModel(input);
        return user.save();
    }

    buildProjection(fields: Record<string, any>): any {
        const projection: any = {};
        for (const key in fields) {
            if (key === 'user' && typeof fields[key] === 'object') { for (const subField of Object.keys(fields[key])) { projection[`user.${subField}`] = 1 } }
            else { projection[key] = 1 }
        }
        return projection;
    }
}
