import { Router } from "express";
import type { Request, Response } from "express";
import { tryCatch } from "../../../../pkg/utils/tryCatch.js";
import { db } from "../../../../pkg/db/db.js";
import { serverData } from "../../../../pkg/db/schema/servers.js";
import { and, asc, eq } from "drizzle-orm";

const router = Router();

router.get("/", async (req: Request, res: Response) => {
    const token = req.query.token;

    const conditions = [];

    if (token !== undefined) {
        conditions.push(eq(serverData.plantToken, `${token}`));
    }

    conditions.push(eq(serverData.active, true));

    const { data, error } = await tryCatch(
        db
            .select()
            .from(serverData)
            .where(and(...conditions))
            .orderBy(asc(serverData.name))
    );

    if (error) {
        return res.status(400).json({ error: error });
    }
    res.status(200).json({ message: "Current Active server", data: data });
});

export default router;
