File size: 6,952 Bytes
bcce530
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
import { NextResponse } from 'next/server'
import prisma from '@/lib/prisma'
import { getAuthUser } from '@/lib/auth'
import { updateProfileSchema, syncProfileSchema, parseBody } from '@/lib/validations'

export const dynamic = 'force-dynamic'

// GET - Fetch user profile
// Only the profile owner can see private fields (email, notification prefs)
export async function GET(req: Request) {
    try {
        const { searchParams } = new URL(req.url)
        const userId = searchParams.get('userId')
        const username = searchParams.get('username')

        if (!userId && !username) {
            return NextResponse.json(
                { error: 'userId or username required' },
                { status: 400 }
            )
        }

        // Check if the viewer is the profile owner
        const authUser = await getAuthUser()
        const isOwner = authUser && (
            (userId && authUser.id === userId) ||
            false // username check happens after fetch
        )

        const user = await prisma.user.findFirst({
            where: userId ? { id: userId } : { username },
            select: {
                id: true,
                name: true,
                username: true,
                image: true,
                bio: true,
                rank: true,
                totalRuns: true,
                totalStars: true,
                totalRemixes: true,
                socialLinks: true,
                createdAt: true,
                // Sensitive fields — only for owner
                email: true,
                notifyEmail: true,
                notifyStars: true,
                notifyRemixes: true,
                _count: {
                    select: {
                        prompts: true,
                        collections: true,
                    },
                },
            },
        })

        if (!user) {
            return NextResponse.json(
                { error: 'User not found' },
                { status: 404 }
            )
        }

        // Strip sensitive fields if not the owner
        const isRealOwner = isOwner || (authUser && authUser.id === user.id)
        if (!isRealOwner) {
            return NextResponse.json({
                id: user.id,
                name: user.name,
                username: user.username,
                image: user.image,
                bio: user.bio,
                rank: user.rank,
                totalRuns: user.totalRuns,
                totalStars: user.totalStars,
                totalRemixes: user.totalRemixes,
                socialLinks: user.socialLinks,
                createdAt: user.createdAt,
                _count: user._count,
            })
        }

        return NextResponse.json(user)
    } catch (error) {
        console.error('Get profile error:', error)
        return NextResponse.json(
            { error: 'Failed to fetch profile' },
            { status: 500 }
        )
    }
}

// PUT - Update user profile — requires authentication (uses server-side auth, not client userId)
export async function PUT(req: Request) {
    try {
        const authUser = await getAuthUser()
        if (!authUser) {
            return NextResponse.json({ error: 'Authentication required' }, { status: 401 })
        }

        const body = await req.json()
        const parsed = parseBody(updateProfileSchema, body)
        if (!parsed.success) return parsed.response

        const {
            name,
            username,
            bio,
            socialLinks,
            image,
            notifyEmail,
            notifyStars,
            notifyRemixes
        } = parsed.data

        // Check if username is taken (if changing username)
        if (username) {
            const existingUser = await prisma.user.findFirst({
                where: {
                    username,
                    NOT: { id: authUser.id },
                },
            })

            if (existingUser) {
                return NextResponse.json(
                    { error: 'Username is already taken' },
                    { status: 409 }
                )
            }
        }

        // Upsert — uses authUser.id from server session, NOT from client body
        const updatedUser = await prisma.user.upsert({
            where: { id: authUser.id },
            create: {
                id: authUser.id,
                email: authUser.email || `${authUser.id}@stackauth.local`,
                name: name || null,
                username: username || null,
                bio: bio || null,
                image: image || null,
                notifyEmail: notifyEmail ?? true,
                notifyStars: notifyStars ?? true,
                notifyRemixes: notifyRemixes ?? true,
            },
            update: {
                ...(name !== undefined && { name }),
                ...(username !== undefined && { username }),
                ...(bio !== undefined && { bio }),
                ...(socialLinks !== undefined && { socialLinks }),
                ...(image !== undefined && { image }),
                ...(notifyEmail !== undefined && { notifyEmail }),
                ...(notifyStars !== undefined && { notifyStars }),
                ...(notifyRemixes !== undefined && { notifyRemixes }),
            },
            select: {
                id: true,
                name: true,
                username: true,
                image: true,
                bio: true,
                socialLinks: true,
                notifyEmail: true,
                notifyStars: true,
                notifyRemixes: true,
            },
        })

        return NextResponse.json(updatedUser)
    } catch (error) {
        console.error('Update profile error:', error)
        return NextResponse.json(
            { error: 'Failed to update profile' },
            { status: 500 }
        )
    }
}

// POST - Create or sync user from Stack Auth
export async function POST(req: Request) {
    try {
        const body = await req.json()
        const parsed = parseBody(syncProfileSchema, body)
        if (!parsed.success) return parsed.response

        const { id, email, name, image } = parsed.data

        // Upsert user - create if doesn't exist, update if does
        const user = await prisma.user.upsert({
            where: { id },
            create: {
                id,
                email,
                name: name || null,
                image: image || null,
                username: email.split('@')[0], // Default username from email
            },
            update: {
                email,
                name: name || null,
                image: image || null,
            },
        })

        return NextResponse.json(user)
    } catch (error) {
        console.error('Sync user error:', error)
        return NextResponse.json(
            { error: 'Failed to sync user' },
            { status: 500 }
        )
    }
}