import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Types, Model } from 'mongoose';
import { Person, PersonDocument } from '@/models/person.model';
import { CreatePersonInput } from './dto/create-person.input';
import { UpdatePersonInput } from './dto/update-person.input';
import { ListPeopleResponse } from './dto/list-people.response';

@Injectable()
export class PeopleService {

    constructor(@InjectModel(Person.name) private readonly personModel: Model<PersonDocument>) { }

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

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

    async create(input: CreatePersonInput): Promise<PersonDocument> { const person = new this.personModel(input); return person.save() }

    async update(uuid: string, input: UpdatePersonInput): Promise<PersonDocument> { const person = await this.personModel.findOne({ uuid }); if (!person) { throw new Error('Person not found') }; person.set(input); return person.save() }

    async delete(uuid: string): Promise<boolean> { const person = await this.personModel.deleteMany({ uuid }); return person.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 }

}
