import { NextRequest, NextResponse } from "next/server";
import { getDb } from "@/lib/db";
import { rmSync, existsSync } from "node:fs";
import { resolve } from "node:path";
import "@/lib/sdk-init";
import { serverConfig } from "@optage/sdk";

const REPOS_PATH = serverConfig.reposPath;

export async function GET(
  _request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const { id } = await params;
  const db = await getDb();
  const { rows } = await db.query("SELECT * FROM repositories WHERE id = $1", [id]);
  if (rows.length === 0) {
    return NextResponse.json({ error: "Not found" }, { status: 404 });
  }
  return NextResponse.json(rows[0]);
}

export async function DELETE(
  _request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const { id } = await params;
  const db = await getDb();
  const { rows } = await db.query("SELECT * FROM repositories WHERE id = $1", [id]);
  if (rows.length === 0) {
    return NextResponse.json({ error: "Not found" }, { status: 404 });
  }
  const repo = rows[0];
  const absoluteSourcePath = resolve(repo.source_path);
  if (
    (repo.source_type === "zip" || repo.source_type === "git") &&
    absoluteSourcePath.startsWith(REPOS_PATH) &&
    existsSync(absoluteSourcePath)
  ) {
    rmSync(absoluteSourcePath, { recursive: true, force: true });
  }
  await db.query("DELETE FROM repositories WHERE id = $1", [id]);
  return NextResponse.json({ ok: true });
}
