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

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

					if (!file) {
						throw Errors.fileNotFound();
					}

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

					// SEC-03: only the file owner or an admin may restore
					const isAdmin = req.user?.roles?.some((r) => ['admin', 'system_admin'].includes(r));
					if (!isAdmin && file.owner_user_id !== req.user?.id) {
						throw Errors.forbidden();
					}

					const success = await fileProvider.restore(req.params.id!);

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