import { Application } from 'express';
import { Resource } from 'express-automatic-routes';
import { Req, Res } from '#interfaces/IApi';
import { verifyWebhookToken } from '#middlewares/webhook-auth';
import webhookService, { WebhookResidentData } from '#services/webhookService';
import { sendSuccess } from '#utils/responseUtils';
import { z } from 'zod';

// Validation schema for webhook resident data
const WebhookResidentSchema = z.object({
	event_id: z.string().optional(),
	type: z.string(),
	c_name: z.string().min(1, 'Name is required'),
	c_dob: z.string().optional(),
	c_tel: z.string().optional(),
	c_sex: z.string().optional(),
	c_cccd: z.string().optional(),
	c_add: z.string().optional(),
});

export default (_express: Application) => {
	return <Resource>{
		post: {
			middleware: [verifyWebhookToken],
			handler: async (req: Req, res: Res) => {
				try {
					// Validate request body
					const validatedData = WebhookResidentSchema.parse(req.body);

					// Extract event_id from validated data
					const { event_id, ...residentData } = validatedData;

					// Process resident data with metadata
					const metadata: {
						eventId?: string;
						ipAddress?: string;
						userAgent?: string;
					} = {};

					if (event_id) {
						metadata.eventId = event_id;
					}
					if (req.ip) {
						metadata.ipAddress = req.ip;
					}
					const userAgent = req.header('user-agent');
					if (userAgent) {
						metadata.userAgent = userAgent;
					}

					const result = await webhookService.processResidentData(residentData as WebhookResidentData, metadata);

					return sendSuccess(res, {
						message: 'Resident data processed successfully',
						resident_id: result.resident.id,
						full_name: result.resident.full_name,
						event_id: result.webhookLog.event_id,
					});
				} catch (error) {
					if (error instanceof z.ZodError) {
						return res.error({
							statusCode: 400,
							message: 'Validation error',
							details: error.issues,
						});
					}
					return res.error(error);
				}
			},
		},
	};
};
