// The Small Business MBA API.
// Boots with auth + health today. Content, community, account, and billing
// routers mount here as they are built. Stripe webhook (raw body) mounts
// BEFORE express.json() when billing is wired.
import express from 'express';
import cors from 'cors';
import helmet from 'helmet';
import rateLimit from 'express-rate-limit';
import { config } from './config.js';
import { errorHandler, notFound } from './middleware/error.js';
import healthRouter from './routes/health.js';
import authRouter from './routes/auth.js';
import contentRouter from './routes/content.js';
import communityRouter from './routes/community.js';
import accountRouter from './routes/account.js';
import billingRouter from './routes/billing.js';
import stripeWebhookRouter from './routes/webhooks_stripe.js';

const app = express();
app.set('trust proxy', 1);
app.use(helmet());

// CORS allowlist: the member app + marketing site (plus localhost for dev).
const allowedOrigins = [
  config.memberAppUrl,
  config.marketingBaseUrl,
  'http://localhost:5173',
  'http://127.0.0.1:5173',
];
app.use(cors({
  origin(origin, cb) { cb(null, !origin || allowedOrigins.includes(origin)); },
  credentials: true,
}));

// Stripe webhook needs the raw body for signature verification, so it mounts
// ABOVE express.json().
app.use('/api/billing/webhook', express.raw({ type: 'application/json' }), stripeWebhookRouter);

app.use(express.json({ limit: '1mb' }));

app.use('/health', healthRouter);

const authLimiter = rateLimit({ windowMs: 15 * 60 * 1000, max: 50, standardHeaders: true, legacyHeaders: false });
app.use('/auth', authLimiter, authRouter);

app.use('/api/content', contentRouter);
app.use('/api/community', communityRouter);
app.use('/api/account', accountRouter);
app.use('/api/billing', billingRouter);

app.use(notFound);
app.use(errorHandler);

app.listen(config.port, () => {
  console.log(`SBM backend listening on :${config.port} (${config.env})`);
});
