import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Types, Model } from 'mongoose';
import { Company, CompanyDocument } from '@/models/company.model';
import { CreateCompanyInput } from './dto/create-company.input';
import { ListCompanyResponse } from './dto/list-company.response';
import { UpdateCompanyInput } from './dto/update-company.input';

@Injectable()
export class CompanyService {

    constructor(@InjectModel(Company.name) private readonly companyModel: Model<CompanyDocument>) { }

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

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

    async create(input: CreateCompanyInput): Promise<CompanyDocument> { const company = new this.companyModel(input); return company.save() }

    async update(uuid: string, input: UpdateCompanyInput): Promise<CompanyDocument> { const company = await this.companyModel.findOne({ uuid }); if (!company) { throw new Error('Company not found') }; company.set(input); return company.save() }

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

}
