import { Application } from 'express';
import { Resource } from 'express-automatic-routes';
import { ContractProvider } from '#providers/ContractProvider';
import { Req, Res } from '#interfaces/IApi';
import verify from '#middlewares/auth';
import { validateId, validateZod } from '#middlewares/validators';
import { ContractUpdateBodySchema } from '#contracts/contract/schema';
import { Errors } from '#interfaces/error';

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

	return <Resource>{
		get: {
			middleware: [verify, validateId],
			handler: async (req: Req, res: Res) => {
				try {
					const data = await provider.getById({ id: req.params.id! });
					if (!data) throw Errors.notFound('Contract');
					return res.sendOk({ data });
				} catch (error) {
					return res.error(error);
				}
			},
		},

		put: {
			middleware: [verify, validateId, validateZod(ContractUpdateBodySchema)],
			handler: async (req: Req, res: Res) => {
				try {
					const current = await provider.getById({ id: req.params.id! });
					if (!current) throw Errors.notFound('Contract');

					const data = await provider.put(req.params.id!, {
						...req.body,
						updated_by: req.user?.id || null,
					});

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

		delete: {
			middleware: [verify, validateId],
			handler: async (req: Req, res: Res) => {
				try {
					await provider.delete(req.params.id!);
					return res.sendOk({ data: true });
				} catch (error) {
					return res.error(error);
				}
			},
		},


	};
};
