import mongoose from "mongoose";

const { Schema, models, model } = mongoose;

export const USER_ROLES = Object.freeze({
	BRANCH: "branch",
	ADMIN: "admin",
	SUPERADMIN: "superadmin",
	DEV: "dev",
});

const userSchema = new Schema(
	{
		username: {
			type: String,
			required: true,
			unique: true,
			index: true,
			trim: true,
			lowercase: true,
			minlength: 3,
			maxlength: 100,
		},
		email: {
			type: String,
			required: true,
			unique: true,
			index: true,
			trim: true,
			lowercase: true,
			maxlength: 200,
		},
		passwordHash: {
			type: String,
			required: true,
		},
		role: {
			type: String,
			required: true,
			enum: Object.values(USER_ROLES),
		},
		branchId: {
			type: String,
			default: null,
			validate: {
				validator: function (value) {
					if (this.role === USER_ROLES.BRANCH) {
						return typeof value === "string" && value.trim().length > 0;
					}
					return true;
				},
				message: "branchId is required for branch users",
			},
		},
		mustChangePassword: {
			type: Boolean,
			default: false,
		},
		passwordResetToken: {
			type: String,
			default: null,
		},
		passwordResetExpiresAt: {
			type: Date,
			default: null,
		},
	},
	{
		timestamps: true,
		toJSON: {
			transform(doc, ret) {
				delete ret.passwordHash;
				delete ret.passwordResetToken;
				return ret;
			},
		},
		toObject: {
			transform(doc, ret) {
				delete ret.passwordHash;
				delete ret.passwordResetToken;
				return ret;
			},
		},
	},
);

// Avoid model overwrite issues in Next.js dev / hot reload
const User = models.User || model("User", userSchema);

export default User;
