import { NextRequest, NextResponse } from 'next/server'
import { getDb } from '@/server/db'
import { getUserIdFromRequest } from '@/app/api/_helpers/session'

export const runtime = 'nodejs'

const MAX_SIZE = 5 * 1024 * 1024 // 5MB

export async function POST(request: NextRequest) {
    try {
        const userId = await getUserIdFromRequest(request)

        if (!userId) {
            return NextResponse.json(
                { ok: false, error: 'Unauthorized' },
                { status: 401 }
            )
        }

        const formData = await request.formData()
        const file = formData.get('thumbnail') as File | null

        if (!file) {
            return NextResponse.json(
                { ok: false, error: 'No file provided' },
                { status: 400 }
            )
        }

        if (!file.type.startsWith('image/')) {
            return NextResponse.json(
                { ok: false, error: 'Invalid file type' },
                { status: 400 }
            )
        }

        if (file.size > MAX_SIZE) {
            return NextResponse.json(
                { ok: false, error: 'File too large' },
                { status: 400 }
            )
        }

        const arrayBuffer = await file.arrayBuffer()
        const buffer = Buffer.from(arrayBuffer)
        const base64 = buffer.toString('base64')
        const thumbnailUrl = `data:${file.type};base64,${base64}`

        const db = await getDb()
        const nowSec = Math.floor(Date.now() / 1000)
        const existing = await db.get<{ room_id: string }>(
            `SELECT room_id FROM room_streams WHERE room_id = ?`,
            [userId]
        )

        if (!existing) {
            await db.run(
                `INSERT INTO room_streams (
                    room_id,
                    title,
                    category,
                    thumbnail_url,
                    chat_disabled,
                    stream_status,
                    created_at,
                    updated_at
                ) VALUES (?, '', '', ?, 0, 'disconnected', ?, ?)`,
                [userId, thumbnailUrl, nowSec, nowSec]
            )
        } else {
            await db.run(
                `UPDATE room_streams SET thumbnail_url = ?, updated_at = ? WHERE room_id = ?`,
                [thumbnailUrl, nowSec, userId]
            )
        }

        return NextResponse.json({
            ok: true,
            thumbnailUrl,
        })
    } catch (error: unknown) {
        console.error('[dashboard/upload-thumbnail] Failed:', error)
        return NextResponse.json(
            {
                ok: false,
                error: error instanceof Error ? error.message : 'Failed to upload thumbnail',
            },
            { status: 500 }
        )
    }
}
