import { Application } from 'express';
import { Resource } from 'express-automatic-routes';
import { SystemConfigProvider } from '#providers/SystemConfigProvider';
import { Req, Res } from '#interfaces/IApi';
import { queryModifier } from '#middlewares/query-modifier';
import verify, { requireAdmin } from '#middlewares/auth';
import { validateZod, validateQueryZod } from '#middlewares/validators';
import { SystemConfigCreateBodySchema, SystemConfigQueryParamsSchema } from '#contracts/system-config/schema';
import { sendSuccess } from '#utils/responseUtils';
import { AuditLogService } from '#services/audit/auditLogService';
import { Errors } from '#interfaces/error';

export default (_express: Application) => {
	const provider = new SystemConfigProvider();

	return <Resource>{
		get: {
			middleware: [verify, requireAdmin, validateQueryZod(SystemConfigQueryParamsSchema), queryModifier],
			handler: async (req: Req, res: Res) => {
				try {
					const data = await provider.getAll(req.payload || {});
					return sendSuccess(res, data);
				} catch (error) {
					return res.error(error);
				}
			},
		},
		post: {
			middleware: [verify, requireAdmin, validateZod(SystemConfigCreateBodySchema)],
			handler: async (req: Req, res: Res) => {
				try {
					// Kiểm tra config_key có tồn tại chưa
					const existingConfig = await provider.getOne({
						where: { config_key: req.body.config_key },
					});
					if (existingConfig) {
						throw Errors.conflict('System config key already exists');
					}

					const data = await provider.create({
						...req.body,
					});

					await AuditLogService.enqueueEntityChangeFromRequest(req, {
						entityType: 'SystemConfig',
						entityId: data.id,
						changeType: 'CREATE',
						payload: {
							before: null,
							after: data.toJSON(),
							changed_fields: Object.keys(req.body),
						},
						reason: `Created system config: ${req.body.config_key}`,
					});

					return sendSuccess(res, data);
				} catch (error) {
					return res.error(error);
				}
			},
		},
	};
};
