import { Hono } from 'hono';
import { cors } from 'hono/cors';

import { auth, type AuthVars } from './auth';

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

// Permissive CORS. The API is a public paid service authed by Bearer
// token, not cookies, so there is no origin trust boundary to defend.
app.use('*', cors({ origin: '*' }));

// Unauthenticated liveness endpoint.
app.get('/', (c) =>
  c.json({
    name: 'tidyindex-api',
    version: '0'
  })
);

// Everything past here requires a valid API key.
app.use('/ping', auth);
app.get('/ping', (c) => {
  const key = c.get('apiKey');
  return c.json({
    message: 'pong',
    account: key.account.email ?? key.account.id,
    plan: key.account.plan,
    key: key.name
  });
});

export default app;
