import { Application } from 'express';
import { Resource } from 'express-automatic-routes';
import { BillProvider } from '#providers/BillProvider';
import { Req, Res } from '#interfaces/IApi';
import { queryModifier } from '#middlewares/query-modifier';
import verify, { requireAdmin } from '#middlewares/auth';
import { validateId } from '#middlewares/validators';
import { validateZod } from '#middlewares/validators';
import { BillUpdateBodySchema } from '#contracts/bill/schema';
import { Errors } from '#interfaces/error';
import { sendSuccess } from '#utils/responseUtils';
import { AuditLogService } from '#services/audit/auditLogService';

export default (_express: Application) => {
	const billProvider = new BillProvider();
	return <Resource>{
		get: {
			middleware: [verify, validateId],
			handler: async (req: Req, res: Res) => {
				try {
					const data = await billProvider.getByIdOptimized(req.params.id!);
					if (!data) {
						throw Errors.notFound('Bill');
					}
					return sendSuccess(res, data);
				} catch (error) {
					return res.error(error);
				}
			},
		},
		put: {
			middleware: [verify, queryModifier, requireAdmin, validateId, validateZod(BillUpdateBodySchema)],
			handler: async (req: Req, res: Res) => {
				try {
					const data = await billProvider.put(req.params.id!, {
						...req.body,
						updated_at: new Date(),
						updated_by: req.user?.id || null,
					});

					// Audit log for bill update
					await AuditLogService.enqueueEntityChangeFromRequest(req, {
						entityType: 'Bill',
						entityId: data.id,
						changeType: 'UPDATE',
						payload: {
							before: null,
							after: data.toJSON(),
							changed_fields: Object.keys(req.body),
						},
						reason: `Updated bill: ${req.body.code || 'N/A'}`,
					});

					return sendSuccess(res, data);
				} catch (error) {
					return res.error(error);
				}
			},
		},
		delete: {
			middleware: [verify, requireAdmin, validateId],
			handler: async (req: Req, res: Res) => {
				try {
					const bill = await billProvider.getById({ id: req.params.id! });
					if (!bill) throw Errors.notFound('Bill');

					const data = await billProvider.delete(req.params.id!);

					// Audit log for bill deletion
					await AuditLogService.enqueueEntityChangeFromRequest(req, {
						entityType: 'Bill',
						entityId: req.params.id!,
						changeType: 'DELETE',
						payload: {
							before: bill.toJSON(),
							after: null,
							changed_fields: Object.keys(bill.toJSON()),
						},
						reason: `Deleted bill: ${bill.code || 'N/A'}`,
					});

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