import {
    FindHeatMapParams,
    IHeatMapAdapter,
    IHeatMap,
    CreateHeatMapParams,
    UpdateHeatMapParams,
    DeleteHeatMapParams,
} from "./HeatMap.Interface";
import { Document, Model, Schema, model } from "mongoose";

export interface IHeatMapDocument extends Omit<IHeatMap, "id">, Document {}

export class HeatMapAdapterMongoose implements IHeatMapAdapter {
    schema: Schema;
    heatMapList: Model<IHeatMapDocument>;

    constructor() {
        this.schema = new Schema({
            companyId: { type: Schema.Types.ObjectId, required: true, ref: "Companie" },
            employeeId: { type: Schema.Types.ObjectId, required: true, ref: "Employee" },
            serviceId: { type: Schema.Types.ObjectId, required: true, ref: "Service" },
            heatMap: { type: Array, required: true },
            heatMapDate: { type: Date, required: true },
        });

        this.heatMapList = model<IHeatMapDocument>("HeatMap", this.schema);
    }

    public async create(data: CreateHeatMapParams): Promise<IHeatMap> {
        return await this.heatMapList.create({
            companyId: data.companyId,
            employeeId: data.employeeId,
            serviceId: data.serviceId,
            heatMap: data.heatmap.heatMap,
            heatMapDate: data.heatMapDate,
        });
    }

    public async update(data: UpdateHeatMapParams): Promise<void> {
        await this.heatMapList.updateOne(
            { _id: data.id },
            {
                companyId: data.companyId,
                employeeId: data.employeeId,
                serviceId: data.serviceId,
                heatMap: data.heatmap.heatMap,
                heatMapDate: data.heatMapDate,
            }
        );
    }

    public async delete(data: DeleteHeatMapParams): Promise<void> {
        let deleteFilter = {};

        if (data.serviceId) {
            deleteFilter = { ...deleteFilter, serviceId: data.serviceId };
        }

        if (data.companyId) {
            deleteFilter = { ...deleteFilter, companyId: data.companyId };
        }

        if (data.employeeId) {
            deleteFilter = { ...deleteFilter, employeeId: data.employeeId };
        }

        if (data.heatMapDate) {
            deleteFilter = { ...deleteFilter, heatMapDate: { $lt: data.heatMapDate } };
        }

        await this.heatMapList.deleteMany(deleteFilter);
    }

    public async findOne(filters: FindHeatMapParams): Promise<IHeatMapDocument | null> {
        return this.heatMapList.findOne(filters).exec();
    }

    public async find(filters: FindHeatMapParams): Promise<IHeatMap[]> {
        return this.heatMapList.find(filters).exec();
    }
}
