import { Request, Response } from 'express';
import validator from 'joi'; // DOCS: https://joi.dev/api
import { Prisma } from '@prisma/client';

// MARK: GET user
const schema_get = validator
	.object({
		sort: validator
			.string()
			.valid(...Object.keys(Prisma.UserScalarFieldEnum))
			.default('id'),

		order: validator.string().valid('asc', 'desc').default('asc'),
		take: validator.number().min(1).max(512),
		skip: validator.number().min(0),
		// This regex ensures that the search string does not contain consecutive asterisks (**) and is at least 3 characters long.
		search: validator.string().min(3).max(20).regex(new RegExp('^(?!.*\\*{2,}).*$')),
		id: validator.number().positive().precision(0)
	})
	.nand('id', 'search'); // Allow id or search. not both.

// MARK: CREATE user
const schema_post = validator.object({
	name: validator.string().min(1).max(32).required(),
	email: validator.string().email().trim().required(),
	code: validator.string().min(4).max(4).trim().regex(new RegExp(/^[0-9]+$/))
});

// MARK: UPDATE user
const schema_patch = validator
	.object({
		id: validator.number().positive().precision(0).required(),
		name: validator.string().min(1).max(32),
		email: validator.string().email().trim(),
		code: validator.string().min(4).max(4).trim().regex(new RegExp(/^[0-9]+$/))
	})
	.or('name', 'email', 'code');

// MARK: DELETE user
const schema_del = validator.object({
	id: validator.number().positive().precision(0).required()
});

// Describe all schemas
const schema_get_desc = schema_get.describe();
const schema_post_desc = schema_post.describe();
const schema_patch_desc = schema_patch.describe();
const schema_del_desc = schema_del.describe();

// GET route
export default async function get(req: Request, res: Response) {
	res.status(200).json({
		GET: schema_get_desc,
		POST: schema_post_desc,
		PATCH: schema_patch_desc,
		DELETE: schema_del_desc
	});
}

export { schema_get, schema_post, schema_patch, schema_del };
