import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Types, Model } from 'mongoose';
import { BuildTypes, BuildTypesDocument } from '@/models/build-types.model';
import { CreateBuildTypesInput } from './dto/create-build-types.input';
import { UpdateBuildTypesInput } from './dto/update-build-types.input';
import { ListBuildTypesResponse } from './dto/list-users.response';

@Injectable()
export class BuildTypesService {

    constructor(@InjectModel(BuildTypes.name) private readonly buildTypesModel: Model<BuildTypesDocument>) { }

    async findAll(projection: any, skip: number, limit: number, sort?: Record<string, 1 | -1>, filters?: Record<string, any>): Promise<ListBuildTypesResponse> {
        const query: any = {}; if (filters && Object.keys(filters).length > 0) { Object.assign(query, filters) };
        const totalCount = await this.buildTypesModel.countDocuments(query).exec();
        const data = await this.buildTypesModel.find(query, projection, { lean: true }).skip(skip).limit(limit).sort(sort).exec();
        return { data, totalCount };
    }

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

    async create(input: CreateBuildTypesInput): Promise<BuildTypesDocument> { const buildTypes = new this.buildTypesModel(input); return buildTypes.save() }

    async update(uuid: string, input: UpdateBuildTypesInput): Promise<BuildTypesDocument> { const buildTypes = await this.buildTypesModel.findOne({ uuid }); if (!buildTypes) { throw new Error('BuildTypes not found') }; buildTypes.set(input); return buildTypes.save() }

    async delete(uuid: string): Promise<boolean> { const buildTypes = await this.buildTypesModel.deleteMany({ uuid }); return buildTypes.deletedCount > 0 }

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