import { serve } from '@hono/node-server';
import { serveStatic } from '@hono/node-server/serve-static';
import { Hono } from 'hono';

import content from './routes/content.js';
import preview from './routes/preview.js';
import publish from './routes/publish.js';
import upload from './routes/upload.js';
import profile from './routes/profile.js';
import users from './routes/users.js';
import { listComments, createComment, deleteComment, login } from './routes/comments.js';
import { requireAuth } from './auth.js';

const SITE_DIR = process.env.SITE_DIR || '/site';
const ADMIN_DIR = process.env.ADMIN_DIR || '/app/admin-dist';
const PORT = Number(process.env.PORT || 3000);

const app = new Hono();

// --- API ---
app.get('/api/health', (c) => c.json({ ok: true, hugo: '0.161.1+extended' }));
// Öffentlich (ohne Login): Dialog lesen + Login fürs Dialog-Widget.
app.get('/api/comments', listComments);
app.post('/api/auth/login', login);
// Alles weitere unter /api/* braucht ein gültiges Supabase-Token.
app.use('/api/*', requireAuth);
app.get('/api/me', (c) => c.json({ email: c.get('email'), isAdmin: c.get('isAdmin') }));
app.post('/api/comments', createComment);
app.delete('/api/comments/:id', deleteComment);
app.route('/api/content', content);
app.route('/api/preview', preview);
app.route('/api/publish', publish);
app.route('/api/upload', upload);
app.route('/api/profile', profile);
app.route('/api/users', users);

// --- Admin-SPA (im Container mitgebaut, unter /admin serviert) ---
app.get('/admin', (c) => c.redirect('/admin/'));
app.use(
  '/admin/*',
  serveStatic({
    root: ADMIN_DIR,
    rewriteRequestPath: (p) => p.replace(/^\/admin/, '') || '/',
  }),
);

// --- Vorschau (gebaut nach preview/ mit --buildDrafts) ---
app.use(
  '/_preview/*',
  serveStatic({
    root: `${SITE_DIR}/preview`,
    rewriteRequestPath: (p) => p.replace(/^\/_preview/, ''),
  }),
);

// Hochgeladene Bilder direkt aus static/ servieren — sofort sichtbar
// (Vorschau, Cover, Profilbild), ohne auf den nächsten Hugo-Build zu warten.
app.use('/images/*', serveStatic({ root: `${SITE_DIR}/static` }));

// --- Live-Site (gebaut nach public/) ---
app.use('/*', serveStatic({ root: `${SITE_DIR}/public` }));

serve({ fetch: app.fetch, port: PORT }, (info) => {
  console.log(`OPENBUREAU CMS läuft auf :${info.port} — Site + API + /_preview`);
});
