import { Application } from 'express';
import { Resource } from 'express-automatic-routes';
import { ApartmentProvider } from '#providers/ApartmentProvider';
import { Req, Res } from '#interfaces/IApi';
import verify, { requireAdmin } from '#middlewares/auth';
import { validateId } from '#middlewares/validators';
import { Errors } from '#interfaces/error';
import { sendSuccess } from '#utils/responseUtils';

export default (_express: Application) => {
	const apartmentProvider = ApartmentProvider.getInstance();
	return <Resource>{
		put: {
			middleware: [verify, requireAdmin, validateId],
			handler: async (req: Req, res: Res) => {
				try {
					const apartment = await apartmentProvider.getById({ id: req.params.id! });

					if (!apartment) {
						throw Errors.notFound('Apartment');
					}

					// Check if apartment is actually deleted
					if (!apartment.deleted_at) {
						throw Errors.validation([
							{
								field: 'apartment',
								code: 'CONFLICT',
								message: { vi: 'Căn hộ chưa bị xóa, không cần khôi phục', en: 'Apartment is not deleted' },
							},
						]);
					}

					const restoreOptions: any = {};
					if (req.user?.id) {
						restoreOptions.restored_by = req.user.id;
					}
					if (req.query.force === 'true') {
						restoreOptions.force = true;
					}
					const success = await apartmentProvider.restore(req.params.id!, restoreOptions);

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