import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Types, Model } from 'mongoose';
import { CreateUserTypesInput } from './dto/create-user-types.input';
import { ListUserTypeResponse } from './dto/list-build-sites.response';
import { UpdateUserTypeInput } from './dto/update-build-sites.input';
import { UserType, UserTypeDocument } from '@/models/user-type.model'

@Injectable()
export class UserTypesService {

    constructor(
        @InjectModel(UserType.name) private readonly userTypesModel: Model<UserTypeDocument>
    ) { }

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

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

    async create(input: CreateUserTypesInput): Promise<UserTypeDocument> { const userType = new this.userTypesModel(input); return userType.save() }

    async update(uuid: string, input: UpdateUserTypeInput): Promise<UserTypeDocument> { const userType = await this.userTypesModel.findOne({ uuid }); if (!userType) { throw new Error('User Type not found') }; userType.set(input); return userType.save() }

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

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

}
