'use strict'

import path, { dirname } from 'path';
import { fileURLToPath } from 'url';
import fs from 'fs';

const dir = dirname(fileURLToPath(import.meta.url));
const root = `${dir}/../../`;


async function plugin(fastify, opts) {
  fastify.get('/docs*', async (req, reply) => {
    if (!fs.existsSync(path.join(root, 'docs/.vitepress/dist/'))) {
      return reply.status(404).send('docs not exists');
    }
    const { params } = req;
    const url = params['*']
    const filePath = url && url[url.length - 1] !== '/' ? path.join(root, 'docs/.vitepress/dist/', url) : path.join(root, 'docs/.vitepress/dist/', url, 'index.html')
    const ext = path.extname(filePath);
    const mime = {
      '.js': 'text/javascript', '.css': 'text/css', '.woff2': 'application/font-woff', '.png': 'image/png', '.svg': 'image/svg+xml', '.jpg': 'image/jpg'
    }[ext];
    const stream = fs.createReadStream(filePath);
    return mime ? reply.type(mime).send(stream) : stream;

  })
}
export default plugin;
