import { logError } from "@/lib/logger";
import { NextRequest, NextResponse } from "next/server";
import { query } from "@/lib/db";

export const runtime = "nodejs";

export async function GET(
  req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;

    const [repoResult, branchesResult, commitsResult] = await Promise.all([
      query<{
        id: string;
        repo_name: string;
        project_id: string;
        project_name: string;
        workspace_name: string;
        default_branch: string;
        is_private: boolean;
        description: string | null;
        created_by: string;
        created_at: Date;
        ai_code_review_enabled: boolean;
        collaborator_count: string;
      }>(
        `SELECT r.id, r.repo_name, r.project as project_id, p.name as project_name,
                COALESCE(w.name, '') as workspace_name, r.default_branch, r.is_private,
                r.description, r.created_by::text as created_by,
                r.created_at::text as created_at, r.ai_code_review_enabled,
                (SELECT COUNT(*) FROM repo_collaborator WHERE repo = r.id)::text as collaborator_count
         FROM repo r
         JOIN project p ON p.id = r.project
         LEFT JOIN workspace w ON w.id = p.workspace_id
         WHERE r.id = $1`,
        [id]
      ),
      query<{
        name: string;
        oid: string;
        head: boolean;
        upstream: string | null;
        created_at: Date;
      }>(
        `SELECT name, oid, head, upstream, created_at::text as created_at
         FROM repo_branch
         WHERE repo = $1
         ORDER BY head DESC, name ASC`,
        [id]
      ),
      query<{
        id: number;
        oid: string;
        author_name: string;
        author_email: string;
        message: string;
        created_at: Date;
      }>(
        `SELECT id, oid, author_name, author_email, message,
                created_at::text as created_at
         FROM repo_commit
         WHERE repo = $1
         ORDER BY created_at DESC
         LIMIT 50`,
        [id]
      ),
    ]);

    if (!repoResult.rows.length) {
      return NextResponse.json({ error: "仓库不存在" }, { status: 404 });
    }

    const r = repoResult.rows[0];
    const repo = {
      id: r.id,
      repoName: r.repo_name,
      projectId: r.project_id,
      projectName: r.project_name,
      workspaceName: r.workspace_name,
      defaultBranch: r.default_branch,
      isPrivate: r.is_private,
      description: r.description,
      createdBy: r.created_by,
      createdAt: String(r.created_at),
      aiCodeReviewEnabled: r.ai_code_review_enabled,
      collaboratorCount: parseInt(r.collaborator_count || "0", 10),
    };

    const branches = branchesResult.rows.map((b) => ({
      name: b.name,
      oid: b.oid,
      isHead: b.head,
      upstream: b.upstream,
      createdAt: String(b.created_at),
    }));

    const commits = commitsResult.rows.map((c) => ({
      id: c.id,
      oid: c.oid,
      shortOid: c.oid.slice(0, 7),
      authorName: c.author_name,
      authorEmail: c.author_email,
      message: c.message,
      shortMessage: c.message.split("\n")[0].slice(0, 80),
      createdAt: String(c.created_at),
    }));

    return NextResponse.json({ repo, branches, commits });
  } catch (e) {
    logError("Repo detail error:", e);
    return NextResponse.json({ error: "服务器错误" }, { status: 500 });
  }
}
