import { Application } from 'express';
import { Resource } from 'express-automatic-routes';
import { ContractFileProvider } from '#providers/ContractFileProvider';
import { Req, Res } from '#interfaces/IApi';
import { queryModifier } from '#middlewares/query-modifier';
import verify from '#middlewares/auth';
import { validateZod } from '#middlewares/validators';
import { ContractFileCreateBodySchema } from '#contracts/contract-file/schema';

export default (_express: Application) => {
	const provider = ContractFileProvider.getInstance();

	return <Resource>{
		get: {
			middleware: [verify, queryModifier],
			handler: async (req: Req, res: Res) => {
				try {
					const data = await provider.getAll(req.payload || {});
					return res.sendOk({ data });
				} catch (error) {
					return res.error(error);
				}
			},
		},

		post: {
			middleware: [verify, validateZod(ContractFileCreateBodySchema)],
			handler: async (req: Req, res: Res) => {
				try {
					const { contract_id, file_id, file_ids } = req.body;
					const fileIdsArray = file_ids || (file_id ? [file_id] : []);
					
					// Create multiple contract-file records
					const data = await provider.bulkCreate(
						fileIdsArray.map((fid: string) => ({
							contract_id,
							file_id: fid,
							created_by: req.user?.id || null,
						}))
					);

					return res.sendOk({ data, statusCode: 201 });
				} catch (error) {
					return res.error(error);
				}
			},
		},
	};
};
