import { PrismaClient, Prisma } from '@prisma/client'; // Database
import { Response } from 'express';
import config from './config.js';
import __path from './path.js';
import log from './log.js';
import fs from 'fs';
import path from 'path';

// Generate .env file for Prisma commands
const dotEnvPath = path.join(__path, '/.env')
const dotEnvExist = !fs.existsSync(dotEnvPath);

fs.writeFileSync(dotEnvPath, `DATABASE_URL="mysql://${config.global.mysql.user}:${config.global.mysql.password}@${config.global.mysql.host}:${config.global.mysql.port}/${config.global.mysql.database}"`);
log.core.info('Generated .env file for Prisma.');
if (dotEnvExist) {
	log.db.error('Please run "npx prisma db push" to synchronize the database.');
	process.exit(1);
}

// TODO: Add errorhandling with some sort of message.
const prisma = new PrismaClient({
	datasources: {
		db: {
			url: `mysql://${config.global.mysql.user}:${config.global.mysql.password}@${config.global.mysql.host}:${config.global.mysql.port}/${config.global.mysql.database}`
		}
	}
});

// FIXME: any
export function handlePrismaError(errorObj: any, res: Response, source: string) {
	log.db.error(source, errorObj);
	if (errorObj instanceof Prisma.PrismaClientKnownRequestError) {
		switch (errorObj.code) {
			// P2002 -> "Unique constraint failed on the {constraint}"
			case 'P2002':
				res.status(409).json({ status: 'ERROR', errorcode: 'DB_ERROR', message: 'The object needs to be unique', meta: errorObj.meta });
				break;

			// P2003 -> "Foreign key constraint failed on the field: {field_name}"
			case 'P2003':
				res.status(404).json({ status: 'ERROR', errorcode: 'DB_ERROR', message: 'Relation object does not exist', meta: errorObj.meta });
				break;

			// P2025 -> "An operation failed because it depends on one or more records that were required but not found. {cause}"
			case 'P2025':
				res.status(404).json({ status: 'ERROR', errorcode: 'DB_ERROR', message: 'Object does not exist', meta: errorObj.meta });
				break;

			default:
				res.status(500).json({ status: 'ERROR', errorcode: 'DB_ERROR', message: 'An error occurred during the database operation' });
				break;
		}
	} else {
		res.status(500).json({ status: 'ERROR', errorcode: 'DB_ERROR', message: 'If you can read this something went terribly wrong!' });
	}
}

export default prisma;

//FIXME: https://www.prisma.io/docs/orm/prisma-client/special-fields-and-types/null-and-undefined


// // Simulate a Prisma error for testing purposes
// throw new Prisma.PrismaClientKnownRequestError(
// 	'Simulated Prisma error for testing',
// 	{ code: 'P2000', clientVersion: 'unknown' } // Example error parameters
// );
