import { Injectable } from '@nestjs/common';
import { Types, Connection, Model } from 'mongoose';
import { getDynamicLivingSpaceModel, LivingSpacesDocument } from '@/models/living-spaces.model';
import { ListLivingSpaceResponse } from './dto/list-living-space.response';
import { CreateLivingSpaceInput } from './dto/create-living-space.input';
import { UpdateLivingSpaceInput } from './dto/update-living-space.input';
import { InjectConnection, InjectModel } from '@nestjs/mongoose';
import { UserTypeDocument } from '@/models/user-type.model';

interface UpdateInput {
    userType?: Types.ObjectId;
    part?: Types.ObjectId | null;
    company?: Types.ObjectId;
    person?: Types.ObjectId;
    expiryStarts?: Date;
    expiryEnds?: Date;
}

@Injectable()
export class LivingSpaceService {

    constructor(
        @InjectConnection() private readonly connection: Connection,
        @InjectModel('UserType') private readonly userTypeModel: Model<UserTypeDocument>
    ) { }

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

    async findById(buildID: string, id: Types.ObjectId, projection?: any): Promise<LivingSpacesDocument | null> {
        const selectedModel = getDynamicLivingSpaceModel(buildID, this.connection);
        return selectedModel.findById(id, projection, { lean: false }).populate({ path: 'company', select: projection?.company }).exec();
    }

    async create(input: CreateLivingSpaceInput): Promise<LivingSpacesDocument> {
        if (!input.buildID) { throw new Error('Build ID is required') }
        const LivingSpaceModel = getDynamicLivingSpaceModel(input.buildID, this.connection);
        const docInput: Partial<LivingSpacesDocument> = {
            build: new Types.ObjectId(input.buildID), part: new Types.ObjectId(input.partID), userType: new Types.ObjectId(input.userTypeID),
            company: new Types.ObjectId(input.companyID), person: new Types.ObjectId(input.personID),
            expiryStarts: input.expiryStarts ? new Date(input.expiryStarts) : new Date(), expiryEnds: input.expiryEnds ? new Date(input.expiryEnds) : new Date('2099-12-31'),
        }; const doc = new LivingSpaceModel(docInput); return await doc.save()
    }

    async update(buildID: string, uuid: string, input: UpdateLivingSpaceInput): Promise<LivingSpacesDocument> {
        if (!buildID) { throw new Error('Build ID is required') }
        const selectedModel = getDynamicLivingSpaceModel(buildID, this.connection);
        const livingSpace = await selectedModel.findOne({ uuid }); const userTypeSelected = await this.userTypeModel.findById(new Types.ObjectId(input.userTypeID)).exec(); const newInput: UpdateInput = {}
        if (userTypeSelected?.isProperty) { if (input?.partID) { newInput.part = new Types.ObjectId(input.partID) } } else { newInput.part = null }
        if (input?.companyID) { newInput.company = new Types.ObjectId(input.companyID) }
        if (input?.personID) { newInput.person = new Types.ObjectId(input.personID) }; if (input?.userTypeID) { newInput.userType = new Types.ObjectId(input.userTypeID) }
        if (input?.expiryStarts) { newInput.expiryStarts = input.expiryStarts }; if (input?.expiryEnds) { newInput.expiryEnds = input.expiryEnds }
        if (!livingSpace) { throw new Error('Company not found') }; livingSpace.set(newInput); return livingSpace.save();
    }

    async delete(buildID: string, uuid: string): Promise<boolean> { if (!buildID) { throw new Error('Build ID is required') } const selectedModel = getDynamicLivingSpaceModel(buildID, this.connection); const company = await selectedModel.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;
    }

}
