import fs from 'node:fs';
import path from 'node:path';
import { createServer } from 'vite';

import { config } from '@opengis/fastify-table/utils.js';

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

console.log({ isProduction });

async function plugin(fastify, opts) {
  const viteServer = !isProduction ? await createServer({
    root: 'admin',
    server: {
      middlewareMode: true,
    },
  }) : null;

  if (!isProduction) {
    const dir1 = process.cwd();
    viteServer.watcher.add(dir1);
    viteServer.watcher.on('all', (d, t) => {
      if (!t.includes('module')) return;
      console.log(d, t);
      viteServer.ws.send({ type: 'full-reload' });
    });

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

      const next = () => new Promise((resolve) => {
        viteServer.middlewares(req.raw, reply.raw, () => resolve());
      });

      await next();
    });
  }

  async function staticFile(req, reply) {
    const assetsDir = 'admin/dist';

    const filePathDist = path.join(assetsDir, req.url.replace('/public/', '/'));
    const filePathAssets = path.join('assets', req.url.replace('/assets', ''));

    const filePath = fs.existsSync(filePathDist) ? filePathDist : filePathAssets; // check dist or assets
    const ext = path.extname(filePath);

    if (!fs.existsSync(filePath)) return { status: 404, message: 'not found' };
    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-Encoding': 'identity' });

    const stream = fs.createReadStream(filePath);
    return mime ? reply.type(mime).send(stream) : stream;
  }
  fastify.get('/assets/*', staticFile);
  fastify.get('/public/*', staticFile);

  fastify.get('*', async (req, reply) => {
    const { user } = req.session?.passport || {};
    // console.log(req.url);
    if (!user && req.url !== '/login') {
      return reply.redirect('/login');
    }
    if (!isProduction) return null; // admin vite
    const stream = fs.createReadStream('admin/dist/index.html');
    return reply.type('text/html').send(stream);
  });
}

export default plugin;
