import { NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { requireAuth } from "@/lib/auth/middleware";
import { scanProjectsInDir } from "@/lib/scanner/auto-scan";

export async function POST(req: Request) {
  const auth = await requireAuth(req);
  if (!auth.ok) return NextResponse.json({ error: "unauthorized" }, { status: auth.status });

  const scanPath = process.env.PM_SCAN_PATH ?? "/data/video-pipeline/LXC4103/project";
  const scanned = await scanProjectsInDir(scanPath);

  let added = 0;
  let updated = 0;
  for (const proj of scanned) {
    const existing = await prisma.project.findUnique({ where: { name: proj.name } });
    if (existing) {
      await prisma.project.update({
        where: { id: existing.id },
        data: {
          path: proj.path,
          gitRemote: proj.gitRemote,
          branch: proj.branch,
          version: proj.version,
          lastCommitHash: proj.lastCommitHash,
          lastCommitMessage: proj.lastCommitMessage,
          lastCommitTime: proj.lastCommitTime,
        },
      });
      updated++;
    } else {
      await prisma.project.create({
        data: {
          name: proj.name,
          path: proj.path,
          source: "auto-scan",
          gitRemote: proj.gitRemote,
          branch: proj.branch,
          version: proj.version,
          lastCommitHash: proj.lastCommitHash,
          lastCommitMessage: proj.lastCommitMessage,
          lastCommitTime: proj.lastCommitTime,
        },
      });
      added++;
    }
  }
  const { eventBus } = await import("@/lib/events/bus");
  eventBus.emit({ type: "scan.complete", added, updated });
  return NextResponse.json({ ok: true, scanned: scanned.length, added, updated, scanPath });
}
