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

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

	return <Resource>{
		get: {
			middleware: [verify, requireAdmin, validateId],
			handler: async (req: Req, res: Res) => {
				try {
					const data = await provider.getById({ id: req.params.id! });
					if (!data) throw Errors.notFound('SystemConfig');
					return sendSuccess(res, data);
				} catch (error) {
					return res.error(error);
				}
			},
		},
		put: {
			middleware: [verify, requireAdmin, validateId, validateZod(SystemConfigUpdateBodySchema)],
			handler: async (req: Req, res: Res) => {
				try {
					const existing = await provider.getById({ id: req.params.id! });
					if (!existing) throw Errors.notFound('SystemConfig');

					// Kiểm tra config_key mới nếu user cố đổi
					if (req.body.config_key && req.body.config_key !== existing.config_key) {
						const conflict = await provider.getOne({
							where: { config_key: req.body.config_key },
						});
						if (conflict) throw Errors.conflict('System config key already exists');
					}

					const data = await provider.put(req.params.id!, {
						...req.body,
						updated_at: new Date(),
					});

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

					return sendSuccess(res, data);
				} catch (error) {
					return res.error(error);
				}
			},
		},
		delete: {
			middleware: [verify, requireAdmin, validateId],
			handler: async (req: Req, res: Res) => {
				try {
					const config = await provider.getById({ id: req.params.id! });
					if (!config) throw Errors.notFound('SystemConfig');

					await provider.delete(req.params.id!, { force: true });

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

					return sendSuccess(res, { message: 'System config deleted successfully' });
				} catch (error) {
					return res.error(error);
				}
			},
		},
	};
};
