import { createHTTPServer, type CreateHTTPContextOptions } from '@trpc/server/adapters/standalone';
import { verifyToken } from '@clerk/backend';
import { projectRouter } from './project-router';
import { revisionsRouter } from './revisions-router';
import { scriptsRouter } from './scripts-router';
import { waitlistRouter } from './waitlist-router';
import { betaRouter } from './beta-router';
import { mailRouter } from './mail-router';
import { teamRouter } from './team-router';
import { analyticsRouter } from './analytics-router';
import type { TRPCContext } from './types';
import type { TRPCError } from '@trpc/server';
import { t } from './router';

// App router combining all routers
export const appRouter = t.router({
  project: projectRouter,
  revisions: revisionsRouter,
  scripts: scriptsRouter,
  waitlist: waitlistRouter,
  beta: betaRouter,
  mail: mailRouter,
  team: teamRouter,
  analytics: analyticsRouter,
} as const);

export type AppRouter = typeof appRouter;

async function authenticateRequest(req: CreateHTTPContextOptions['req']): Promise<string | undefined> {
  const authHeader = req.headers['authorization'];
  if (!authHeader) {
    return undefined;
  }

  const match = authHeader.match(/^Bearer\s+(.+)$/i);
  if (!match || !match[1]) {
    return undefined;
  }

  const token = match[1];

  try {
    const verified = await verifyToken(token, {
      secretKey: process.env.CLERK_SECRET_KEY,
    });
    return verified.sub;
  } catch {
    return undefined;
  }
}

// Create tRPC HTTP server - db is loaded lazily to avoid requiring Turso env vars at import time
export function createTRPCServer(port: number = 8080) {
  const server = createHTTPServer({
    router: appRouter,
    createContext: async (opts: CreateHTTPContextOptions): Promise<TRPCContext> => {
      const { db } = await import('../../src/db/config/migrations');
      const clerkUserId = await authenticateRequest(opts.req);
      return {
        clerkUserId,
        db,
      };
    },
    onError: ({ error, path }: { error: TRPCError; path: string | undefined }) => {
      console.error(`tRPC error on ${path}: [internal error]`);
    },
  });

  server.listen(port, () => {
    console.log(`tRPC server listening on port ${port}`);
  });

  return server;
}

export default appRouter;
