import { NextRequest, NextResponse } from 'next/server';
import { signJwt, setSessionCookie } from '@/core/auth';
import { isBootstrapStandaloneEnabled } from '@/core/auth/standalone';

/** Avoid opening SQLite during `next build` (parallel workers → SQLITE_BUSY). */
export const dynamic = 'force-dynamic';

const DEFAULT_TTL_SEC = 86_400;

function safeInternalTarget(raw: string | null): string {
  const v = (raw ?? '/').trim() || '/';
  if (!v.startsWith('/') || v.startsWith('//') || v.includes('://') || v.includes('\0')) {
    return '/';
  }
  return v;
}

/**
 * One-shot session bootstrap for standalone mode.
 * Redirect target must stay on the same origin (path + optional query).
 */
export async function GET(req: NextRequest): Promise<NextResponse> {
  if (!isBootstrapStandaloneEnabled()) {
    return NextResponse.json({ error: 'Not found' }, { status: 404 });
  }

  const { getAllWorkspaces } = await import('@/lib/db/repositories');
  const workspaces = getAllWorkspaces();
  if (workspaces.length === 0) {
    return NextResponse.json(
      {
        error: 'No workspace in the database. Run: npm run db:seed-dev (or wait for Docker entrypoint to seed).',
      },
      { status: 503 },
    );
  }

  const ttl = Math.min(
    Math.max(60, Number(process.env.MAILFORGE_STANDALONE_SESSION_TTL_SEC) || DEFAULT_TTL_SEC),
    86400 * 7,
  );

  const token = await signJwt(
    {
      userId: process.env.MAILFORGE_STANDALONE_USER_ID?.trim() || 'local-dev',
      workspaceIds: workspaces.map((w) => w.id),
      permissions: ['*'],
      email: process.env.MAILFORGE_STANDALONE_EMAIL?.trim() || 'dev@local.test',
      displayName: process.env.MAILFORGE_STANDALONE_DISPLAY_NAME?.trim() || 'Local user',
    },
    ttl,
  );

  const next = safeInternalTarget(req.nextUrl.searchParams.get('next'));
  const target = new URL(next, req.url);
  if (target.origin !== new URL(req.url).origin) {
    return NextResponse.redirect(new URL('/', req.url));
  }

  const res = NextResponse.redirect(target);
  setSessionCookie({ response: res, token, maxAge: ttl });
  return res;
}
