import { FastifyInstance, FastifyRequest } from "fastify";
import fp from "fastify-plugin";
import { eq } from "drizzle-orm";
import { tenants } from "../../db/schema";

export default fp(async (server: FastifyInstance) => {
    server.addHook("preHandler", async (req, reply) => {
        const host = req.headers.host?.split(":")[0]; // Domain ohne Port
        if (!host) {
            reply.code(400).send({ error: "Missing host header" });
            return;
        }
        // Tenant aus DB laden
        const rows = await server.db
            .select()
            .from(tenants)
            .where(eq(tenants.portalDomain, host))
            .limit(1);
        const tenant = rows[0];


        if(!tenant) {
            // Multi Tenant Mode
            (req as any).tenant = null;
        }else {
            // Tenant ins Request-Objekt hängen
            (req as any).tenant = tenant;
        }

    });
});

// Typ-Erweiterung
declare module "fastify" {
    interface FastifyRequest {
        tenant?: {
            id: string;
            name: string;
            domain?: string;
            subdomain?: string;
            settings?: Record<string, any>;
        };
    }
}
