import { Request, Response } from 'express';
import db, { handlePrismaError } from '../../../../handlers/db.js'; // Database
import log from '../../../../handlers/log.js';
import { schema_get } from './user_codecheck_schema.js';

// MARK: GET user codecheck
async function get(req: Request, res: Response) {
	const { error, value } = schema_get.validate(req.query);
	if (error) {
		log.api?.debug('GET user codecheck Error:', req.query, value, error.details[0].message);
		res.status(400).json({ status: 'ERROR', errorcode: 'VALIDATION_ERROR', message: error.details[0].message });
	} else {
		log.api?.debug('GET user codecheck Success:', req.query, value);

		await db.user
			.findUnique({
				where: {
					id: value.id
				}
			})
			.catch((err) => {
				handlePrismaError(err, res, 'GET user codecheck');
			})
			.then((result) => {
				// user has no code OR code must match
				// result?.code === ''		-> user exists and has no code
				// result?.code === null	-> user exists and has no code
				// result?.code === undefined	-> user does not exists
  				// value.code === result?.code	-> If user exists and has no code this matches
				res.status(200).json(result?.code === '' || result?.code === null || result?.code === undefined || result?.code === value.code);
				//log.api?.debug(result, result?.code);
			});
	}
}

export default { get };
