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();

const UpdateDbConnectionSchema = z.object({
	connection_string_env: z.string().optional(),
	user_table: z.string().optional(),
	user_id_column: z.string().optional(),
	email_column: z.string().optional(),
	json_profile_column: z.string().optional().nullable(),
	status: z.enum(['active', 'inactive']).optional(),
});

export default (_express: Application) => {
	return <Resource>{
		get: {
			middleware: [requireAdminApiKey],
			handler: async (req: Req, res: Res) => {
				const { id } = req.params as any;
				const conn = await svc.getById(id);
				if (!conn) return res.error({ message: 'Not found', code: 'NOT_FOUND' });
				return sendSuccess(res, conn);
			},
		},
		put: {
			middleware: [requireAdminApiKey, validateZod(UpdateDbConnectionSchema)],
			handler: async (req: Req, res: Res) => {
				const { id } = req.params as any;
				const conn = await svc.update(id, req.body);
				return sendSuccess(res, conn);
			},
		},
		delete: {
			middleware: [requireAdminApiKey],
			handler: async (req: Req, res: Res) => {
				const { id } = req.params as any;
				await svc.delete(id);
				return res.status(204).send();
			},
		},
	};
};
