import { FastifyInstance } from "fastify";
import { eq } from "drizzle-orm";
import { devices } from "../../../db/schema";

export default async function deviceRoutes(fastify: FastifyInstance) {
    fastify.get<{
        Params: {
            externalId: string;
        };
    }>(
        "/devices/by-external-id/:externalId",
        async (request, reply) => {
            const { externalId } = request.params;

            const device = await fastify.db
                .select({
                    id: devices.id,
                    name: devices.name,
                    type: devices.type,
                    tenant: devices.tenant,
                    externalId: devices.externalId,
                    created_at: devices.createdAt,
                })
                .from(devices)
                .where(
                    eq(devices.externalId, externalId)

                )
                .limit(1)
                .then(rows => rows[0]);

            if (!device) {
                return reply.status(404).send({
                    message: "Device not found",
                });
            }

            return reply.send(device);
        }
    );
}
