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 check user code
async function get(req: Request, res: Response) {
	const { error, value } = schema_get.validate(req.query);
	if (error) {
		log.api?.debug('GET check user code 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 check user code Success:', req.query, value);

		await db.user
			.findUnique({
				where: {
					id: value.id
				}
			})
			.catch((err) => {
				handlePrismaError(err, res, 'GET check user code');
			})
			.then((result) => {
				// user has no code OR code must match
				res.status(200).json(result?.code === '' || value.code === result?.code);
				// log.api?.debug('result', result);
			});
		// res.status(200).json({ count, result });
		// res.status(404).json({ status: 'ERROR', errorcode: 'NOT_FOUND', message: 'Could not find specified object' });
	}
}

export default { get };
