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 { validateZod, validateQueryZod } from '#middlewares/validators';
import { BillCreateBodySchema } from '#contracts/bill/schema';
import { QueryParamsSchema } from '#contracts/shared';
import { sendSuccess } from '#utils/responseUtils';
import { AuditLogService } from '#services/audit/auditLogService';
import { generateBillCode } from '#utils/billCodeGenerator';

export default (_express: Application) => {
	const billProvider = new BillProvider();
	return <Resource>{
		get: {
			middleware: [verify, validateQueryZod(QueryParamsSchema), queryModifier],
			handler: async (req: Req, res: Res) => {
				try {
					const payload = { ...(req.payload || {}) } as any;
					const data = await billProvider.getAllOptimized(payload, { user: req.user });
					return sendSuccess(res, data);
				} catch (error) {
					return res.error(error);
				}
			},
		},
		post: {
			middleware: [verify, requireAdmin, validateZod(BillCreateBodySchema)],
			handler: async (req: Req, res: Res) => {
				try {
					// Generate unique code automatically
					const code = await generateBillCode();
					const data = await billProvider.createWithItems({
						...req.body,
						code,
						created_by: req.user?.id || null,
					});

					// Audit log for bill creation
					await AuditLogService.enqueueEntityChangeFromRequest(req, {
						entityType: 'Bill',
						entityId: data.id,
						changeType: 'CREATE',
						payload: {
							before: null,
							after: data.toJSON(),
							changed_fields: Object.keys(req.body),
						},
						reason: `Created new bill: ${code}`,
					});

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