import { db } from "@/lib/db"
import { NextResponse } from "next/server";
import fetchUserWithImpersonation from "@/lib/fetch-user-impersonation";
import axios from "axios";
import { env } from "process";
import { TwitchUpdateAuthorization } from "@/lib/twitch";
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 { searchParams } = new URL(req.url)
        const groupId = searchParams.get('groupId') as string
        const pageString = searchParams.get('page') as string
        const search = searchParams.get('search') as string

        if (!groupId && search != 'all')
            return NextResponse.json({ message: 'Something went wrong', error: null, value: null }, { status: 400 })

        let page = parseInt(pageString)
        if (isNaN(page) || page === undefined || page === null)
            page = 0

        let chatters: { userId: string, groupId: string, chatterId: bigint, chatterLabel: string }[]

        if (search != 'all')
            chatters = await db.chatterGroup.findMany({
                where: {
                    userId: user.id,
                    groupId
                }
            })
        else
            chatters = await db.chatterGroup.findMany({
                where: {
                    userId: user.id
                }
            })

        const paginated = search == 'all' ? chatters : chatters.slice(page * 50, (page + 1) * 50)
        if (!paginated || paginated.length == 0)
            return NextResponse.json([])

        const ids = chatters.map(c => c.chatterId)
        const idsString = 'id=' + ids.map(i => i.toString()).reduce((a, b) => a + '&id=' + b)

        const auth = await TwitchUpdateAuthorization(user.id)
        if (!auth)
            return NextResponse.json({ message: 'Unauthorized', error: null, value: null }, { status: 403 })

        const users = await axios.get("https://api.twitch.tv/helix/users?" + idsString, {
            headers: {
                "Authorization": "Bearer " + auth.access_token,
                "Client-Id": env.TWITCH_BOT_CLIENT_ID
            }
        })

        if (!users)
            return NextResponse.json({ message: 'No users found', error: null, value: null }, { status: 400 })

        if (users.data.data.length == 0)
            return NextResponse.json([])

        return NextResponse.json(users.data.data.map((u: any) => ({ id: u.id, username: u.login })));
    } catch (error) {
        return NextResponse.json({ message: 'Failed to get', error: error, value: null }, { status: 500 })
    }
}

const groupIdSchema = z.string({
    required_error: "Group ID should be available.",
    invalid_type_error: "Group ID must be a string"
}).regex(/^[\w\-\=]{1,40}$/, "Group ID must contain only letters, numbers, dashes, underscores & equal signs.")

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 { groupId, users }: { groupId: string, users: { id: number, username: string }[] } = await req.json();
        if (!groupId)
            return NextResponse.json({ message: 'groupId must be set.', error: null, value: null }, { status: 400 });
        if (!users)
            return NextResponse.json({ message: 'users must be set.', error: null, value: null }, { status: 400 });

        const groupIdValidation = await groupIdSchema.safeParseAsync(groupId)
        if (!groupIdValidation.success)
            return NextResponse.json({ message: 'groupId does not meet requirements.', error: JSON.parse(groupIdValidation.error['message'])[0], value: null }, { status: 400 })

        const chatters = await db.chatterGroup.createMany({
            data: users.map(u => ({ userId: user.id, chatterId: u.id, groupId, chatterLabel: u.username }))
        });

        return NextResponse.json(chatters, { status: 200 });
    } catch (error) {
        return NextResponse.json({ message: 'Failed to create', 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 groupId = searchParams.get('groupId') as string
        const ids = searchParams.get('ids') as string
        if (!groupId)
            return NextResponse.json({ message: 'groupId must be set.', error: null, value: null }, { status: 400 });

        if (!ids)
            return NextResponse.json({ message: 'ids must be set.', error: null, value: null }, { status: 400 });

        const groupIdValidation = await groupIdSchema.safeParseAsync(groupId)
        if (!groupIdValidation.success)
            return NextResponse.json({ message: 'groupId does not meet requirements.', error: JSON.parse(groupIdValidation.error['message'])[0], value: null }, { status: 400 })

        const chatters = await db.chatterGroup.deleteMany({
            where: {
                userId: user.id,
                chatterId: {
                    in: ids.split(',').map(i => parseInt(i)).filter(i => !i || !isNaN(i))
                },
                groupId
            }
        })

        return NextResponse.json(chatters);
    } catch (error) {
        return NextResponse.json({ message: 'Failed to delete.', error: error, value: null }, { status: 500 })
    }
}