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

export default (_express: Application) => {
	const technicianProvider = new TechnicianProvider();
	return <Resource>{
		get: {
			middleware: [verify, requireAdmin, validateQueryZod(QueryParamsSchema), queryModifier],
			handler: async (req: Req, res: Res) => {
				try {
					const data = await technicianProvider.getAllWithUser(req.payload || {});
					return sendSuccess(res, data);
				} catch (error) {
					return res.error(error);
				}
			},
		},
		post: {
			middleware: [verify, requireAdmin, validateZod(TechnicianCreateBodySchema)],
			handler: async (req: Req, res: Res) => {
				try {
					const data = await technicianProvider.createWithUser({
						...req.body,
						created_by: req.user?.id || null,
						updated_by: req.user?.id || null,
					});

					// Audit log for technician creation
					await AuditLogService.enqueueEntityChangeFromRequest(req, {
						entityType: 'Technician',
						entityId: data.id,
						changeType: 'CREATE',
						payload: {
							before: null,
							after: data,
							changed_fields: Object.keys(req.body),
						},
						reason: `Created new technician: ${req.body.first_name || ''} ${req.body.last_name || ''}`.trim() || 'N/A',
					});
								
					return sendSuccess(res, data);
				} catch (error) {
					return res.error(error);
				}
			},
		},
	};
};
