import { NextRequest, NextResponse } from 'next/server'
import { getDb } from '@/server/db'
import { getUserIdFromRequest } from '@/app/api/_helpers/session'
import {
    CREATE_LIVE_INPUT_HASH_ACTION,
    DASHBOARD_API_HASH_HEADER,
    verifyDashboardActionHash,
} from '@/lib/api/dashboardActionHash'
import {
    applyLiveInputSyncToRoomStream,
    createCloudflareLiveInput,
    mapLiveInputToRoomStreamFields,
} from '@/lib/streams/cloudflareLiveInput'
import { sanitizeStreamTitleForDashboard } from '@/lib/streams/streamTitle'

export const runtime = 'nodejs'
export const dynamic = 'force-dynamic'

/** 透過 Cloudflare API 建立 Live Input，並寫入 room_streams.live_input_identifier */
export async function POST(request: NextRequest) {
    try {
        const userId = await getUserIdFromRequest(request)
        if (!userId) {
            return NextResponse.json({ ok: false, error: 'Unauthorized' }, { status: 401 })
        }

        const hashToken = request.headers.get(DASHBOARD_API_HASH_HEADER)?.trim() ?? ''
        if (!verifyDashboardActionHash(userId, CREATE_LIVE_INPUT_HASH_ACTION, hashToken)) {
            return NextResponse.json(
                { ok: false, error: 'Invalid or expired x-hash' },
                { status: 403 }
            )
        }

        const db = await getDb()
        const stream = await db.get<{
            room_id: string
            live_input_identifier: string | null
            title: string | null
        }>(
            `SELECT room_id, live_input_identifier, title FROM room_streams WHERE room_id = ?`,
            [userId]
        )

        const existing = String(stream?.live_input_identifier ?? '').trim()
        if (existing) {
            return NextResponse.json(
                { ok: false, error: 'Stream key already exists' },
                { status: 409 }
            )
        }

        const created = await createCloudflareLiveInput({ name: userId })
        if (!created.ok) {
            return NextResponse.json({ ok: false, error: created.error }, { status: 502 })
        }

        const { result, liveInputIdentifier } = created
        const existingTitle = sanitizeStreamTitleForDashboard(stream?.title, userId)
        const syncFields = mapLiveInputToRoomStreamFields(result, {
            titleFallback: existingTitle,
        })
        const nowSec = Math.floor(Date.now() / 1000)

        if (!stream) {
            await db.run(
                `INSERT INTO room_streams (
                    room_id,
                    title,
                    category,
                    thumbnail_url,
                    live_input_identifier,
                    stream_token,
                    chat_disabled,
                    stream_status,
                    created_at,
                    updated_at
                ) VALUES (?, ?, '', '', ?, ?, 0, ?, ?, ?)`,
                [
                    userId,
                    syncFields.title ?? '',
                    liveInputIdentifier,
                    syncFields.stream_token,
                    syncFields.stream_status,
                    nowSec,
                    nowSec,
                ]
            )
        } else {
            await db.run(
                `UPDATE room_streams
                 SET live_input_identifier = ?,
                     stream_token = COALESCE(NULLIF(?, ''), stream_token),
                     stream_status = ?,
                     updated_at = ?
                 WHERE room_id = ?`,
                [
                    liveInputIdentifier,
                    syncFields.stream_token,
                    syncFields.stream_status,
                    nowSec,
                    userId,
                ]
            )
        }

        await applyLiveInputSyncToRoomStream(db, userId, result, {
            titleFallback: existingTitle,
            nowSec,
        })

        return NextResponse.json({ ok: true })
    } catch (error: unknown) {
        console.error('[create-live-input] failed:', error)
        return NextResponse.json(
            {
                ok: false,
                error: error instanceof Error ? error.message : 'Failed to create stream key',
            },
            { status: 500 }
        )
    }
}
