import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Types, Model } from 'mongoose';
import { BuildIban, BuildIbanDocument } from '@/models/build.model';
import { ListBuildIbanResponse } from './dto/list-build-ibans.response';
import { CreateBuildIbanInput } from './dto/create-build-ibans.input';
import { UpdateBuildIbanInput } from './dto/update-build-ibans.input';

@Injectable()
export class BuildIbanService {

    constructor(@InjectModel(BuildIban.name) private readonly buildIbanModel: Model<BuildIbanDocument>) { }

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

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

    async create(input: CreateBuildIbanInput): Promise<BuildIbanDocument> { const buildIban = new this.buildIbanModel(input); return buildIban.save() }

    async update(uuid: string, input: UpdateBuildIbanInput): Promise<BuildIbanDocument> { const buildIban = await this.buildIbanModel.findOne({ uuid }); if (!buildIban) { throw new Error('BuildIban not found') }; buildIban.set(input); return buildIban.save() }

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

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

}
