/**
 * GET /api/projects/[projectId]/dev-server-logs?id=ds_…
 *
 * Returns the tail of /var/log/vibn-dev/<id>.log from the project dev
 * container so the Preview tab can show errors without MCP-only tools.
 */
import { NextResponse } from 'next/server';
import { authSession } from '@/lib/auth/session-server';
import { query } from '@/lib/db-postgres';
import { execInDevContainer } from '@/lib/dev-container';

const ID_RE = /^ds_[a-f0-9]+$/;

export async function GET(
  req: Request,
  { params }: { params: Promise<{ projectId: string }> },
) {
  try {
    const { projectId } = await params;
    const session = await authSession();
    if (!session?.user?.email) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const { searchParams } = new URL(req.url);
    const id = searchParams.get('id')?.trim() ?? '';
    if (!id || !ID_RE.test(id)) {
      return NextResponse.json({ error: 'Invalid or missing id' }, { status: 400 });
    }

    const rows = await query<{ one: number }>(
      `SELECT 1 AS one
         FROM fs_dev_servers d
         JOIN fs_projects p ON p.id = d.project_id
         JOIN fs_users u ON u.id = p.user_id
        WHERE d.id = $1 AND d.project_id = $2 AND u.data->>'email' = $3
        LIMIT 1`,
      [id, projectId, session.user.email],
    );
    if (rows.length === 0) {
      return NextResponse.json({ error: 'Not found' }, { status: 404 });
    }

    const safeId = id.replace(/[^a-z0-9_]/gi, '');
    const r = await execInDevContainer({
      projectId,
      command: `tail -n 200 /var/log/vibn-dev/${safeId}.log 2>/dev/null || echo "(no log file for ${safeId})"`,
      timeoutMs: 12_000,
    });

    return NextResponse.json({
      logs: (r.stdout ?? '').trim() || '(empty)',
    });
  } catch (err) {
    console.error('[dev-server-logs]', err);
    return NextResponse.json(
      { error: err instanceof Error ? err.message : 'Failed to read logs' },
      { status: 502 },
    );
  }
}
