import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Types, Model } from 'mongoose';
import { User, UserDocument } from '@/models/user.model';
import { CreateUserInput } from './dto/create-user.input';
import { UpdateUserInput } from './dto/update-user.input';
import { ListUsersResponse } from './dto/list-users.response';

@Injectable()
export class UsersService {

    constructor(@InjectModel(User.name) private readonly userModel: Model<UserDocument>) { }

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

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

    async create(input: CreateUserInput): Promise<UserDocument> { const user = new this.userModel(input); return user.save() }

    async update(uuid: string, input: UpdateUserInput): Promise<UserDocument> { const user = await this.userModel.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.userModel.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 }

}
