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, validateQueryZod } from '#middlewares/validators';
import { z } from 'zod';
import { AdminDbConnectionService } from '#services/admin/adminService';
import { sendSuccess } from '#utils/responseUtils';

const svc = new AdminDbConnectionService();

const CreateDbConnectionSchema = z.object({
	app_code: z.string().min(1),
	provider: z.string().default('postgresql'),
	connection_string_env: z.string().min(1),
	user_table: z.string().default('users'),
	user_id_column: z.string().default('id'),
	email_column: z.string().default('email'),
	json_profile_column: z.string().optional(),
	status: z.enum(['active', 'inactive']).default('active'),
});

const ListDbConnectionQuery = z.object({
	page: z.coerce.number().int().positive().default(1),
	pageSize: z.coerce.number().int().min(1).max(100).default(20),
	status: z.enum(['active', 'inactive']).optional(),
});

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

const TestConnectionSchema = z.object({
	connection_string: z.string().min(1),
});

export default (_express: Application) => {
	return <Resource>{
		get: {
			middleware: [requireAdminApiKey, validateQueryZod(ListDbConnectionQuery)],
			handler: async (req: Req, res: Res) => {
				const { page, pageSize, status } = req.query as any;
				const result = await svc.list({ page, pageSize, status });
				return sendSuccess(res, result);
			},
		},
		post: {
			middleware: [requireAdminApiKey, validateZod(CreateDbConnectionSchema)],
			handler: async (req: Req, res: Res) => {
				const conn = await svc.create(req.body);
				res.status(201);
				return sendSuccess(res, conn);
			},
		},
	};
};
