import { Application } from 'express';
import { Resource } from 'express-automatic-routes';
import { IncidentFileProvider } from '#providers/IncidentFileProvider';
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 { IncidentFileCreateBodySchema } from '#contracts/incident-file/schema';
import { QueryParamsSchema } from '#contracts/shared';
import { sendSuccess } from '#utils/responseUtils';

export default (_express: Application) => {
	const incidentFileProvider = new IncidentFileProvider();
	return <Resource>{
		get: {
			middleware: [verify, validateQueryZod(QueryParamsSchema), queryModifier],
			handler: async (req: Req, res: Res) => {
				try {
					const data = await incidentFileProvider.getAll(req.payload || {});
					return sendSuccess(res, data);
				} catch (error) {
					return res.error(error);
				}
			},
		},
		post: {
			middleware: [verify, validateZod(IncidentFileCreateBodySchema)],
			handler: async (req: Req, res: Res) => {
				try {
					const { incident_id, file_id, file_ids } = req.body;
					const fileIdsArray = file_ids || (file_id ? [file_id] : []);
					
					// Create multiple incident-file records
					const data = await incidentFileProvider.bulkCreate(
						fileIdsArray.map((fid: string) => ({
							incident_id,
							file_id: fid,
							created_by: req.user?.id || null,
						}))
					);
					return sendSuccess(res, data);
				} catch (error) {
					return res.error(error);
				}
			},
		},
	};
};
