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';
import { ListBuildPartsResponse } from './dto/list-build-parts.response';
import { UpdateBuildPartsInput } from './dto/update-build-parts.input';
import { Build, BuildDocument } from '@/models/build.model';

@Injectable()
export class BuildPartsService {

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

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

    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 getBuildID = await this.buildModel.findById(input?.buildId, { _id: 1 }, { lean: true }).exec();
        if (getBuildID) { input.buildId = new Types.ObjectId(getBuildID._id) };
        if (input?.directionId) { input.directionId = new Types.ObjectId(input?.directionId) };
        if (input?.typeId) { input.typeId = new Types.ObjectId(input?.typeId) };
        const buildParts = new this.buildPartsModel(input); return buildParts.save()
    }

    async update(uuid: string, input: UpdateBuildPartsInput): Promise<BuildPartsDocument> {
        const buildParts = await this.buildPartsModel.findOne({ _id: new Types.ObjectId(uuid) }); if (!buildParts) { throw new Error('BuildParts not found') };
        if (input?.buildId) { const getBuildID = await this.buildModel.findById(input?.buildId, { _id: 1 }, { lean: true }).exec(); if (getBuildID) { input.buildId = new Types.ObjectId(getBuildID._id) } };
        if (input?.directionId) { input.directionId = new Types.ObjectId(input?.directionId) };
        if (input?.typeId) { input.typeId = new Types.ObjectId(input?.typeId) }; buildParts.set(input); return buildParts.save()
    }

    async delete(uuid: string): Promise<boolean> { console.log(uuid); const buildParts = await this.buildPartsModel.deleteMany({ _id: new Types.ObjectId(uuid) }); return buildParts.deletedCount > 0 }

    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;
    }
}
