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

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

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

		post: {
			middleware: [verify, validateZod(ContractCreateBodySchema)],
			handler: async (req: Req, res: Res) => {
				try {
					const data = await provider.create({
						...req.body,
						created_by: req.user?.id || null,
					});

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