import { db } from "@/lib/db"
import { NextResponse } from "next/server";
import fetchUserWithImpersonation from "@/lib/fetch-user-impersonation";
import { z } from "zod";

export async function GET(req: Request) {
    try {
        const user = await fetchUserWithImpersonation(req)
        if (!user) {
            return NextResponse.json({ message: 'Unauthorized.', error: null, value: null }, { status: 401 });
        }

        const actions = await db.group.findMany({
            where: {
                userId: user.id
            }
        })

        return NextResponse.json(actions.map(({ userId, ...attrs }) => attrs));
    } catch (error) {
        return NextResponse.json({ message: 'Something went wrong', error: error, value: null }, { status: 500 })
    }
}

const groupNameSchema = z.string({
    required_error: "Group name is required.",
    invalid_type_error: "Group name must be a string"
}).regex(/^[\w\-\s]{1,20}$/, "Group name must contain only letters, numbers, spaces, dashes, and underscores.")

export async function POST(req: Request) {
    try {
        const user = await fetchUserWithImpersonation(req)
        if (!user) {
            return NextResponse.json({ message: 'Unauthorized.', error: null, value: null }, { status: 401 });
        }

        const { name, priority }: { name: string, priority: number } = await req.json();
        if (!name)
            return NextResponse.json({ message: 'name does not exist.', error: null, value: null }, { status: 400 });
        const groupNameValidation = await groupNameSchema.safeParseAsync(name)
        if (!groupNameValidation.success)
            return NextResponse.json({ message: 'name does not meet requirements.', error: JSON.parse(groupNameValidation.error['message'])[0], value: null }, { status: 400 })

        const group = await db.group.create({
            data: {
                userId: user.id,
                name: name.toLowerCase(),
                priority
            }
        });

        return NextResponse.json(group, { status: 200 });
    } catch (error) {
        return NextResponse.json({ message: 'Something went wrong', error: error, value: null }, { status: 500 })
    }
}

export async function PUT(req: Request) {
    try {
        const user = await fetchUserWithImpersonation(req)
        if (!user) {
            return NextResponse.json({ message: 'Unauthorized.', error: null, value: null }, { status: 401 });
        }

        const { id, name, priority }: { id: string, name: string, priority: number } = await req.json();
        if (!id)
            return NextResponse.json({ message: 'id does not exist.', error: null, value: null }, { status: 400 });
        if (!name && !priority)
            return NextResponse.json({ message: 'Either name or priority must not be null.', error: null, value: null }, { status: 400 });
        if (name) {
            const groupNameValidation = await groupNameSchema.safeParseAsync(name)
            if (!groupNameValidation.success)
                return NextResponse.json({ message: 'name does not meet requirements.', error: JSON.parse(groupNameValidation.error['message'])[0], value: null }, { status: 400 })
        }

        let data: any = {}
        if (name)
            data = { ...data, name: name.toLowerCase() }
        if (priority)
            data = { ...data, priority }

        const group = await db.group.update({
            where: {
                id
            },
            data: data
        });

        return NextResponse.json(group, { status: 200 });
    } catch (error) {
        return NextResponse.json({ message: 'Something went wrong', error: error, value: null }, { status: 500 })
    }
}

export async function DELETE(req: Request) {
    try {
        const user = await fetchUserWithImpersonation(req)
        if (!user) {
            return NextResponse.json({ message: 'Unauthorized.', error: null, value: null }, { status: 401 });
        }

        const { searchParams } = new URL(req.url)
        const id = searchParams.get('id') as string
        const group = await db.group.delete({
            where: {
                id
            }
        })

        return NextResponse.json(group);
    } catch (error) {
        return NextResponse.json({ message: 'Something went wrong', error: error, value: null }, { status: 500 })
    }
}