// routes/notifications.routes.ts
import { FastifyInstance } from 'fastify';
import { NotificationService, UserDirectory } from '../modules/notification.service';
import { eq } from "drizzle-orm";
import { authUsers } from "../../db/schema";

// Beispiel: E-Mail aus eigener User-Tabelle laden
const getUserDirectory: UserDirectory = async (server:FastifyInstance, userId, tenantId) => {
    const rows = await server.db
        .select({ email: authUsers.email })
        .from(authUsers)
        .where(eq(authUsers.id, userId))
        .limit(1)
    const data = rows[0]
    if (!data) return null;
    return { email: data.email };
};

export default async function notificationsRoutes(server: FastifyInstance) {
    const svc = new NotificationService(server, getUserDirectory);

    server.post('/notifications/trigger', async (req, reply) => {
        try {
            const res = await svc.trigger(req.body as any);
            reply.send(res);
        } catch (err: any) {
            server.log.error(err);
            reply.code(500).send({ error: err.message });
        }
    });
}
