File size: 2,414 Bytes
a905864
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/**
 * Save Issues/PRs Route
 * 
 * POST /api/issues/save
 * Save GitHub-fetched issues/PRs to the database for persistence
 */

import { NextRequest, NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { createIssue, getIssueByGithubId } from "@/lib/db/queries/issues";

export async function POST(request: NextRequest) {
    try {
        const user = await getCurrentUser(request);
        if (!user) {
            return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
        }

        const body = await request.json();
        const { issues } = body;

        if (!issues || !Array.isArray(issues)) {
            return NextResponse.json({
                error: "issues array is required"
            }, { status: 400 });
        }

        let saved = 0;
        let skipped = 0;

        for (const issue of issues) {
            // Skip if already in database (by githubIssueId)
            if (issue.githubIssueId) {
                const existing = await getIssueByGithubId(issue.githubIssueId);
                if (existing) {
                    skipped++;
                    continue;
                }
            }

            // Save to database
            try {
                await createIssue({
                    githubIssueId: issue.githubIssueId || issue.number,
                    number: issue.number,
                    title: issue.title,
                    body: issue.body || '',
                    authorName: issue.authorName,
                    repoId: issue.repoId,
                    repoName: issue.repoName,
                    owner: issue.owner,
                    repo: issue.repo,
                    htmlUrl: issue.htmlUrl,
                    state: issue.state || 'open',
                    isPR: issue.isPR || false,
                });
                saved++;
            } catch (err) {
                console.log('Could not save issue:', issue.number, err);
                skipped++;
            }
        }

        return NextResponse.json({
            success: true,
            saved,
            skipped,
            total: issues.length,
        });

    } catch (error: any) {
        console.error("POST /api/issues/save error:", error);
        return NextResponse.json({
            error: "Failed to save issues",
            detail: error.message
        }, { status: 500 });
    }
}