import { Document, Model, Schema, model } from "mongoose";
import {
    CreateRepeatsParams,
    FindRepeatsParams,
    IRepeat,
    IRepeatsAdapter,
} from "./Repeats.Interface";

export interface IRepeatDocument extends Omit<IRepeat, "id">, Document {}

export class RepeatsAdapterMongoose implements IRepeatsAdapter {
    schema: Schema;
    repeatsList: Model<IRepeatDocument>;

    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" },
            clientId: { type: Schema.Types.ObjectId, required: true, ref: "Client" },
            discountId: { type: Schema.Types.ObjectId, required: false, ref: "Discount" },
            weekDay: { type: Number, required: true },
            startHour: { type: Number, required: true },
            length: { type: Number, required: true },
            disabledDates: { type: Array, required: false },
            creationDate: { type: Date, required: true, default: Date.now },
        });

        this.repeatsList = model<IRepeatDocument>("Repeat", this.schema);
    }

    public async create(data: CreateRepeatsParams): Promise<IRepeat> {
        const { discountId, sessionUser, ...repeatData } = data;
        const repeat = await this.repeatsList.create(repeatData);

        if (discountId) {
            repeat.set("discountId", discountId);
            await repeat.save();
        }
        return repeat;
    }

    public async delete(id: string): Promise<void> {
        await this.repeatsList.deleteOne({ _id: id });
    }

    public async find(filters: FindRepeatsParams): Promise<IRepeat[]> {
        return this.repeatsList.find(filters).exec();
    }

    public async findOne(filters: FindRepeatsParams): Promise<IRepeatDocument | null> {
        return this.repeatsList.findOne(filters).exec();
    }
}
