import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Types, Model } from 'mongoose';
import { Build, BuildDocument } from '@/models/build.model';
import { CreateBuildInput } from './dto/create-build.input';

@Injectable()
export class BuildService {

    constructor(@InjectModel(Build.name) private readonly buildModel: Model<BuildDocument>) { }

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

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

    async create(input: CreateBuildInput): Promise<BuildDocument> { const buildArea = new this.buildModel(input); return buildArea.save() }

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