import { Hono } from 'hono';
import { serve } from '@hono/node-server';
import { serveStatic } from '@hono/node-server/serve-static';
import { renderer } from './views/layout';
import { HomePage } from './views/page';
import { promptsApi } from './api/prompts';
import { settingsApi } from './api/settings';
import { generateApi } from './api/generate';
import { translateApi } from './api/translate';
import { imagesApi } from './api/images';
import { authApi, authMiddleware } from './api/auth';
import { db, applyMigrations } from './db';

// Bootstrap migrations before server starts
applyMigrations();

export type Env = {};
export type Variables = { db: typeof db };

const app = new Hono<{ Bindings: Env; Variables: Variables }>();

// Inject db on every request
app.use('*', async (c, next) => {
  c.set('db', db);
  await next();
});

// JSX renderer
app.use('*', renderer);

// Auth on all /api/* except /api/auth/check
app.use('/api/*', authMiddleware);

// Pages
app.get('/', (c) => c.render(<HomePage />));

// JSON API
app.route('/api/auth', authApi);
app.route('/api/prompts', promptsApi);
app.route('/api/settings', settingsApi);
app.route('/api/generate', generateApi);
app.route('/api/translate', translateApi);
app.route('/api/images', imagesApi);

// Static assets (./public/*)
app.use('/styles.css', serveStatic({ path: './public/styles.css' }));
app.use('/app.js', serveStatic({ path: './public/app.js' }));
app.use('/fonts/*', serveStatic({ root: './public' }));

const port = Number(process.env.PORT || 8787);
serve({ fetch: app.fetch, port }, (info) => {
  console.log(`[promptlib] http://localhost:${info.port}`);
});
