import { FastifyRequest, FastifyReply, FastifyInstance } from 'fastify';
import { publicLinkService } from '../../modules/publiclinks.service';
import dayjs from 'dayjs'; // Falls nicht installiert: npm install dayjs
import { buildProfileCalendarSubscriptionFeed, loadProfileByCalendarSubscriptionToken } from '../../utils/calendarSubscription';

export default async function publiclinksNonAuthenticatedRoutes(server: FastifyInstance) {
    server.get("/api/public/calendar/subscriptions/:token.ics", async (req, reply) => {
        const { token } = req.params as { token: string }

        try {
            const profile = await loadProfileByCalendarSubscriptionToken(server, token)

            if (!profile || !profile.active) {
                return reply.code(404).send({ error: "Kalender-Abo nicht gefunden" })
            }

            const icsFeed = await buildProfileCalendarSubscriptionFeed(server, profile)

            reply.header("Content-Type", "text/calendar; charset=utf-8")
            reply.header("Content-Disposition", `inline; filename="fedeo-${profile.id}.ics"`)
            reply.header("Cache-Control", "private, max-age=300")

            return reply.send(icsFeed)
        } catch (error: any) {
            server.log.error(error)
            return reply.code(500).send({ error: "Interner Server Fehler" })
        }
    })

    server.get("/workflows/context/:token", async (req, reply) => {
        const { token } = req.params as { token: string };
        const pin = req.headers['x-public-pin'] as string | undefined;

        try {
            const context = await publicLinkService.getLinkContext(server, token, pin);
            return reply.send(context);
        } catch (error: any) {
            if (error.message === "Link_NotFound") return reply.code(404).send({ error: "Link nicht gefunden" });
            if (error.message === "Pin_Required") return reply.code(401).send({ error: "PIN erforderlich", requirePin: true });
            if (error.message === "Pin_Invalid") return reply.code(403).send({ error: "PIN falsch", requirePin: true });

            server.log.error(error);
            return reply.code(500).send({ error: "Interner Server Fehler" });
        }
    });

    server.post("/workflows/submit/:token", async (req, reply) => {
        const { token } = req.params as { token: string };
        const pin = req.headers['x-public-pin'] as string | undefined;
        const body = req.body as any;

        try {
            const quantity = parseFloat(body.quantity) || 0;

            // Wir nutzen das vom User gewählte deliveryDate
            // Falls kein Datum geschickt wurde, Fallback auf Heute
            const baseDate = body.deliveryDate ? dayjs(body.deliveryDate) : dayjs();

            const payload = {
                ...body,
                // Wir mappen das deliveryDate auf die Zeitstempel
                // Start ist z.B. 08:00 Uhr am gewählten Tag, Ende ist Start + Menge
                startDate: baseDate.hour(8).minute(0).toDate(),
                endDate: baseDate.hour(8).add(quantity, 'hour').toDate(),
                deliveryDate: baseDate.format('YYYY-MM-DD')
            };

            const result = await publicLinkService.submitFormData(server, token, payload, pin);
            return reply.code(201).send(result);

        } catch (error: any) {
            server.log.error(error);
            return reply.code(500).send({ error: "Fehler beim Speichern", details: error.message });
        }
    });
}
