import { Application } from 'express';
import { Resource } from 'express-automatic-routes';
import { Req, Res } from '#interfaces/IApi';
import { requireAdminApiKey } from '#middlewares/admin-api-key';
import { validateZod } from '#middlewares/validators';
import { z } from 'zod';
import { AdminDbConnectionService } from '#services/admin/adminService';
import { sendSuccess } from '#utils/responseUtils';

const svc = new AdminDbConnectionService();

export default (_express: Application) => {
	return <Resource>{
		post: {
			middleware: [requireAdminApiKey, validateZod(z.object({ connection_string: z.string().min(1) }))],
			handler: async (req: Req, res: Res) => {
				const { connection_string } = req.body as any;
				const result = await svc.testConnection(connection_string);
				if (result.success) {
					return sendSuccess(res, result);
				}
				res.status(400);
				return sendSuccess(res, result);
			},
		},
	};
};
