import { Application } from 'express';
import { Resource } from 'express-automatic-routes';
import { PostProvider } from '#providers/PostProvider';
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 { PostCreateBodySchema } from '#contracts/post/schema';
import { QueryParamsSchema } from '#contracts/shared';
import { sendSuccess } from '#utils/responseUtils';
import { AuditLogService } from '#services/audit/auditLogService';

export default (_express: Application) => {
	const postProvider = new PostProvider();

	return <Resource>{
		get: {
			middleware: [verify, validateQueryZod(QueryParamsSchema), queryModifier],
			handler: async (req: Req, res: Res) => {
				try {
					const isAdmin = req.user?.roles?.some((r) => ['admin', 'system_admin'].includes(r)) ?? false;
					const data = await postProvider.getAllOptimized(req.payload || {}, req.user?.id, isAdmin);
					return sendSuccess(res, data);
				} catch (error) {
					return res.error(error);
				}
			},
		},

		post: {
			middleware: [verify, requireAdmin, validateZod(PostCreateBodySchema)],
			handler: async (req: Req, res: Res) => {
				try {
					const { title, content, thumbnailId, targetType, targetIds, isFeatured, status, publishedAt } = req.body;

					const data = await postProvider.createWithTargets({
						title,
						content,
						thumbnail_id: thumbnailId ?? null,
						target_type: targetType,
						target_ids: targetIds ?? [],
						is_featured: isFeatured ?? false,
						status: status ?? 'draft',
						published_at: publishedAt ? new Date(publishedAt) : null,
						author_id: req.user!.id,
						created_by: req.user?.id ?? null,
					});

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

					const detail = await postProvider.getByIdOptimized(data.id);
					return sendSuccess(res, detail);
				} catch (error) {
					return res.error(error);
				}
			},
		},
	};
};
