import { FastifyRequest, FastifyReply, FastifyInstance } from 'fastify';
import { publicLinkService } from '../../modules/publiclinks.service';


export default async function publiclinksAuthenticatedRoutes(server: FastifyInstance) {
    server.post("/publiclinks", async (req, reply) => {
        try {
            const tenantId = 21; // Hardcoded für Test, später: req.user.tenantId

            const { name, isProtected, pin, customToken, config, defaultProfileId } = req.body as { name:string, isProtected:boolean, pin:string, customToken:string, config:Object, defaultProfileId:string};

            const newLink = await publicLinkService.createLink(server, tenantId,
                name,
                isProtected,
                pin,
                customToken,
                config,
                defaultProfileId);

            return reply.code(201).send({
                success: true,
                data: {
                    id: newLink.id,
                    token: newLink.token,
                    fullUrl: `/public/${newLink.token}`, // Helper für Frontend
                    isProtected: newLink.isProtected
                }
            });

        } catch (error: any) {
            server.log.error(error);

            // Einfache Fehlerbehandlung
            if (error.message.includes("bereits vergeben")) {
                return reply.code(409).send({ error: error.message });
            }

            return reply.code(500).send({ error: "Fehler beim Erstellen des Links", details: error.message });
        }
    })
}
