import { Hono } from 'hono';
import { cors } from 'hono/cors';
import { ledgers } from './routes/ledgers';
import { serveStatic } from './serve-static';

// The BASE_URL env var is only needed when deploying under a subpath
// (e.g. BASE_URL=https://example.com/splint). If unset or set to a
// root URL like http://localhost:3000, BASE_PATH defaults to '/'.
const BASE_URL = process.env.BASE_URL || '';
const BASE_PATH = BASE_URL
  ? (() => {
      try {
        const p = new URL(BASE_URL).pathname.replace(/\/+$/, '');
        return p || '/';
      } catch {
        return '/';
      }
    })()
  : '/';

// TODO: Add hashcash challenge to create new ledgers?
const app = new Hono();

// CORS: allow all origins
// There are no cookies or auth tokens to steal — the server only stores ciphertext.
// There's no auth, so an attacker can hit the API directly regardless.
// Open CORS is a neutral choice here: restricting origins adds no real protection,
// and leaving it open avoids surprising devs who proxy the API through a different origin in custom deployments.
app.use('*', cors());

// API Routes — mounted under BASE_PATH so they work at /splint/ledgers/*
const api = new Hono();
api.route('/ledgers', ledgers);
app.route(BASE_PATH === '/' ? '/' : BASE_PATH, api);

// In production, serve the built web app from ../web/dist/
// The basePath parameter lets the static file handler strip the /splint prefix
// before resolving file paths, so assets at dist/assets/* are found correctly.
const isProd = process.env.NODE_ENV === 'production';
if (isProd) {
  serveStatic(app, BASE_PATH === '/' ? '' : BASE_PATH);
}

// Verify database connection before accepting requests
import { db } from './db';
try {
  await db.execute('SELECT 1');
} catch (err) {
  console.error('Database connection failed:', err);
  process.exit(1);
}

const port = parseInt(process.env.PORT || '3000');
console.log(
  `Server running on port ${port} (${isProd ? 'production' : 'development'})` +
    (BASE_PATH && BASE_PATH !== '/' ? ` basePath=${BASE_PATH}` : '')
);

export default {
  port,
  fetch: app.fetch,
};
