import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Types, Model } from 'mongoose';
import { BuildParts, BuildPartsDocument } from '@/models/build-parts.model';
import { CreateBuildPartsInput } from './dto/create-build-part.input';

@Injectable()
export class BuildPartsService {

    constructor(@InjectModel(BuildParts.name) private readonly buildPartsModel: Model<BuildPartsDocument>) { }

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

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

    async create(input: CreateBuildPartsInput): Promise<BuildPartsDocument> {
        const buildParts = new this.buildPartsModel(input);
        return buildParts.save();
    }

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