import { Application } from 'express';
import { Resource } from 'express-automatic-routes';
import { Req, Res } from '#interfaces/IApi';
import verify from '#middlewares/auth';
import { sendSuccess } from '#utils/responseUtils';
import { ChangePasswordBodySchema } from '#contracts/auth/schema';
import { PasswordService } from '#services/auth/passwordService';

export default (_express: Application) => {
	return <Resource>{
		put: {
			middleware: [verify],
			handler: async (req: Req, res: Res) => {
				try {
					const { old_password, new_password } = req.body;

					// Validate request body
					const validation = ChangePasswordBodySchema.safeParse({ old_password, new_password });
					if (!validation.success) {
						return res.error({
							code: 'VALIDATION_ERROR',
							message: 'Validation failed',
							details: validation.error.issues.map((err: any) => ({
								field: err.path.join('.'),
								code: err.code,
								messages: {
									vi: err.message,
									en: err.message,
								},
							})),
						});
					}

					// Change password using PasswordService
					await PasswordService.changePassword(req.user!.id, old_password, new_password);

					return sendSuccess(res, {
						success: true,
						message: 'Password changed successfully',
					});
				} catch (error) {
					return res.error(error);
				}
			},
		},
	};
};
