import { Application } from 'express';
import { Resource } from 'express-automatic-routes';
import { ResidentProvider } from '#providers/ResidentProvider';
import { Req, Res } from '#interfaces/IApi';
import { queryModifier } from '#middlewares/query-modifier';
import verify, { requireAdmin } from '#middlewares/auth';
import { validateId } from '#middlewares/validators';
import { validateZod } from '#middlewares/validators';
import { ResidentUpdateBodySchema } from '#contracts/resident/schema';
import { Errors } from '#interfaces/error';
import { sendSuccess } from '#utils/responseUtils';
import { AuditLogService } from '#services/audit/auditLogService';
import { User } from '#models/User';

export default (_express: Application) => {
	const residentProvider = new ResidentProvider();
	return <Resource>{
		get: {
			middleware: [verify, validateId],
			handler: async (req: Req, res: Res) => {
				try {
					const data = await residentProvider.getByIdWithResidenceAndDocuments({ id: req.params.id! });
					if (!data) throw Errors.notFound('Resident');
					const isAdmin = req.user?.roles?.some((r) => ['admin', 'system_admin'].includes(r));
					if (!isAdmin && req.user?.id !== data.user_id) {
						throw Errors.forbidden();
					}
					return sendSuccess(res, data);
				} catch (error) {
					return res.error(error);
				}
			},
		},
		put: {
			middleware: [verify, queryModifier, validateId, validateZod(ResidentUpdateBodySchema)],
			handler: async (req: Req, res: Res) => {
				try {
					const resident = await residentProvider.getById({ id: req.params.id! });
					if (!resident) throw Errors.notFound('Resident');
					const isAdmin = req.user?.roles?.some((r) => ['admin', 'system_admin'].includes(r));
					if (!isAdmin && req.user?.id !== resident.user_id) {
						throw Errors.forbidden();
					}

					const beforeData = { ...resident.toJSON() };

					// Filter out fields that are not in residents table or should not be updated
					const { bed_ids: _bed_ids, move_in_at: _move_in_at, avatar_id: avatarId, ...updateData } = req.body;

					await residentProvider.put(req.params.id!, {
						...updateData,
						updated_at: new Date(),
						updated_by: req.user?.id || null,
					});

					// Update user's avatar_id if provided and resident has a linked user
					if (avatarId && resident.user_id) {
						await User.update(
							{ avatar_id: avatarId, updated_at: new Date() },
							{ where: { id: resident.user_id } },
						);
					}

					// Fetch updated data with residence info
					const updatedData = await residentProvider.getByIdWithResidence({ id: req.params.id! });

					// Calculate changed fields
					const changedFields = Object.keys(req.body).filter((key) => {
						return (beforeData as any)[key] !== req.body[key];
					});

					// Audit log for resident update
					await AuditLogService.enqueueEntityChangeFromRequest(req, {
						entityType: 'Resident',
						entityId: req.params.id!,
						changeType: 'UPDATE',
						payload: {
							before: beforeData,
							after: updatedData,
							changed_fields: changedFields,
						},
						reason: `Updated resident fields: ${changedFields.join(', ')}`,
					});

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

					const data = await residentProvider.delete(req.params.id!);

					// Audit log for resident deletion
					await AuditLogService.enqueueEntityChangeFromRequest(req, {
						entityType: 'Resident',
						entityId: req.params.id!,
						changeType: 'DELETE',
						payload: {
							before: resident.toJSON(),
							after: null,
							changed_fields: Object.keys(resident.toJSON()),
						},
						reason: `Deleted resident: ${resident.full_name || 'N/A'}`,
					});

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