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

const dir = dirname(fileURLToPath(import.meta.url));
const root = `${dir}/../..`;
import { config } from '@opengis/fastify-table/utils.js';

const isProduction = process.env.NODE_ENV === 'production' || config.production;

async function plugin(fastify) {
  // vite server
  if (!isProduction) {
    const vite = await import('vite');

    const viteServer = await vite.createServer({
      server: {
        middlewareMode: true,
      },
    });
    // hot reload
    viteServer.watcher.on('all', function (d, t) {
      if (!t.includes('module')) return;
      console.log(d, t);
      viteServer.ws.send({ type: 'full-reload' });
    });

    // this is middleware for vite's dev servert
    fastify.addHook('onRequest', async (req, reply) => {
      const { user } = req.session?.passport || {};

      if (!user && req.url.startsWith('/login')) {
        return reply.redirect(`/login?redirect=${req.url}`);
      }

      const next = () => new Promise((resolve) => {
        viteServer.middlewares(req.raw, reply.raw, () => resolve());
      });
      await next();
    });
    fastify.get('*', async () => { });
    return;
  }

  // From Build
  fastify.get('*', async (req, reply) => {
    const { user } = req.session?.passport || {};

    if (!user && req.url.startsWith('/login')) {
      return reply.redirect(`/login?redirect=${req.url}`);
    }
    const stream = fs.createReadStream('dist/index.html');
    return reply.type('text/html').send(stream);
  });

  const fileSize = {}
  async function staticFile(req, reply) {
    const assetsDir = 'dist';
    const filePath = path.join(root, assetsDir, req.url);
    const ext = path.extname(filePath);

    if (!fs.existsSync(filePath)) return { status: 404, message: 'not found' }
    fileSize[filePath] = fileSize[filePath] || fs.statSync(filePath).size;
    const mime = {
      '.js': 'text/javascript', '.css': 'text/css', '.woff2': 'application/font-woff', '.png': 'image/png', '.svg': 'image/svg+xml', '.jpg': 'image/jpg',
    }[ext];
    reply.headers({ 'Cache-control': 'max-age=3600, public', 'Content-length': fileSize[filePath], 'Content-Encoding': 'identity' });

    const stream = fs.createReadStream(filePath);
    return mime ? reply.type(mime).send(stream) : stream;
  }

  fastify.get('/assets/*', staticFile);
  fastify.get('/public/*', staticFile);
}

export default plugin;
