import mongoose, { Schema, models, Document } from "mongoose";
import { BaseSchema, Base } from "./base";

const expiresDate = () => new Date(Date.now() + 30 * 24 * 60 * 60 * 1000);

interface ICollectionToken {
    tokens: { prefix: string; token: string }[];
    default: string;
}

interface IUser extends Base, Document {
    expiresAt?: Date;
    resetToken?: string;
    password: string;
    history?: string[];
    tag: string;
    email: string;
    phone: string;
    collectionTokens: ICollectionToken;
    person: mongoose.Types.ObjectId;
    type?: mongoose.Types.ObjectId;
}

const CollectionTokenSchema = new Schema<ICollectionToken>(
    {
        tokens: { type: [{ prefix: { type: String, required: true }, token: { type: String, required: true } }], default: [], required: false },
        default: { type: String, required: true, default: "" },
    },
    { _id: false }
);


const UsersSchema = new Schema<IUser>(
    {
        ...BaseSchema,
        expiresAt: { type: Date, default: expiresDate, required: false },
        resetToken: { type: String, required: false },
        password: { type: String, required: true },
        history: {
            type: [String],
            validate: [(val: string[]) => val.length <= 3, "History can have max 3 items"],
            default: [],
            required: false,
        },
        tag: { type: String, required: true },
        email: { type: String, required: true, unique: true },
        phone: { type: String, required: true, unique: true },
        collectionTokens: {
            type: CollectionTokenSchema,
            default: () => ({ tokens: [], default: "" }),
            required: true,
        },
        person: { type: Schema.Types.ObjectId, ref: "Person", required: true },
        type: { type: Schema.Types.ObjectId, ref: "UserType", required: false },
    },
    { timestamps: true }
);

const Users = models.Users || mongoose.model("Users", UsersSchema);

export { Users };
export type { IUser, ICollectionToken };
