import { db } from "@/lib/db"
import { NextResponse } from "next/server"
import { z } from "zod"

export async function GET(request: Request, context: { params: { username: string } }) {
    const { username } = context.params

    const idSchema = z.string()
    const zod = idSchema.safeParse(username)

    if (!zod.success) {
        return NextResponse.json(zod.error, { status: 400 })
    }

    try {
        const user = await db.user.findUnique({
            where: {
                username,
            },

            select: {
                id: true,
                name: true,
                username: true,
                email: true,
                image: true,
                banner: true,

                createdAt: true,
                bio: true,
                location: true,
                website: true,
                followers: true,
                following: true,

                _count: {
                    select: {
                        followers: true,
                        following: true,
                    },
                },
            },
        })

        return NextResponse.json(user, { status: 200 })
    } catch (error: any) {
        return NextResponse.json(error.message, { status: 500 })
    }
}

export async function PUT(request: Request) {
    const {
        userId,
        name,
        bio,
        location,
        website,
        banner,
        image,
    } = await request.json()

    const userSchema = z
        .object({
            userId: z.string().cuid(),
            name: z.string().min(1).max(50),
            bio: z.string().max(160).optional(),
            location: z.string().max(30).optional(),
            website: z.string().max(100).optional(),
            banner: z.string().optional(),
            image: z.string().optional(),
        })
        .strict()

    const zod = userSchema.safeParse({
        userId,
        name,
        bio,
        location,
        website,
        banner,
        image,
    })

    if (!zod.success) {
        return NextResponse.json(zod.error, { status: 400 })
    }

    try {
        const user = await db.user.update({
            where: {
                id: userId,
            },
            data: {
                name,
                bio,
                location,
                website,
                banner,
                image,
            },
        })

        return NextResponse.json(user, { status: 200 })
    } catch (error: any) {
        return NextResponse.json(error.message, { status: 500 })
    }
}