import type { FastifyInstance, FastifyPluginAsync } from "fastify";
import type { FastifyReply } from "fastify/types/reply";
import type { FastifyRequest } from "fastify/types/request";
import { readFile } from "fs/promises";

interface FaviconOptions {
    path: string;
}

const faviconPlugin: FastifyPluginAsync<FaviconOptions> = async (fastify: FastifyInstance, options: FaviconOptions): Promise<void> => {
    let faviconData: Buffer | null = null;

    try {
        faviconData = await readFile(options.path);
    } catch (err) {
        console.error("Error reading favicon:", err);
    }

    fastify.get("/favicon.ico", async (_request: FastifyRequest, reply: FastifyReply): Promise<void> => {
        if (faviconData) {
            const contentType = options.path.endsWith(".gif") ? "image/gif" : "image/x-icon";
            reply.header("Content-Type", contentType)
                .header("Cache-Control", "public, max-age=86400") // 1 day
                .send(faviconData);
        } else {
            reply.status(404).send({
                code: 404,
                error: "FILE_NOT_FOUND",
                message: "Favicon not found"
            });
        }
    });
};

export default faviconPlugin as FastifyPluginAsync<FaviconOptions>;
