import { Injectable } from '@nestjs/common';
import { UpdateBuildAddressInput } from './dto/update-build-address.input';
import { ListBuildAddressInput } from './dto/list-build-address.response';
import { CreateBuildAddressInput } from './dto/create-build-address.input';
import { InjectModel } from '@nestjs/mongoose';
import { Types, Model } from 'mongoose';
import { BuildAddress, BuildAddressDocument } from '@/models/build-address.model';

@Injectable()
export class BuildAddressService {

    constructor(@InjectModel(BuildAddress.name) private readonly buildAddressModel: Model<BuildAddressDocument>) { }

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

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

    async create(input: CreateBuildAddressInput): Promise<BuildAddressDocument> { const user = new this.buildAddressModel(input); return user.save() }

    async update(uuid: string, input: UpdateBuildAddressInput): Promise<BuildAddressDocument> { const user = await this.buildAddressModel.findOne({ uuid }); if (!user) { throw new Error('User not found') }; user.set(input); console.dir({ uuid, input }, { depth: null }); return user.save() }

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

    buildProjection(fields: Record<string, any>): Record<string, 1> { const projection: Record<string, 1> = {}; for (const key in fields) { projection[key] = 1 }; return projection }

}
