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

export default (_express: Application) => {
	const provider = ContractFileProvider.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('ContractFile');
					return res.sendOk({ data });
				} catch (error) {
					return res.error(error);
				}
			},
		},

		put: {
			middleware: [verify, validateId, validateZod(ContractFileUpdateBodySchema)],
			handler: async (req: Req, res: Res) => {
				try {
					// Get current file to check contract_id
					const current = await provider.getById({ id: req.params.id! });
					if (!current) throw Errors.notFound('ContractFile');

					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);
				}
			},
		},
	};
};
