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

export const runtime = 'nodejs'

const MAX_CONTENT_LENGTH = 10000

async function resolveTargetUserId(userKey: string) {
    const key = String(userKey ?? '').trim()
    if (!key) return null
    const db = await getDb()
    const userId = await resolveUserKeyToUserId(db, key)
    return userId ? { db, userId } : null
}

export async function POST(request: NextRequest, ctx: { params: { id: string } }) {
    const sessionUserId = await getUserIdFromRequest(request)
    if (!sessionUserId) {
        return NextResponse.json({ ok: false, error: 'UNAUTHORIZED' }, { status: 401 })
    }

    const resolved = await resolveTargetUserId(ctx?.params?.id ?? '')
    if (!resolved) {
        return NextResponse.json({ ok: false, error: 'NOT_FOUND' }, { status: 404 })
    }

    if (sessionUserId !== resolved.userId) {
        return NextResponse.json({ ok: false, error: 'FORBIDDEN' }, { status: 403 })
    }

    let body: { content?: string; thumbnailUrl?: string | null }
    try {
        body = await request.json()
    } catch {
        return NextResponse.json({ ok: false, error: 'INVALID_BODY' }, { status: 400 })
    }

    const content = String(body.content ?? '').trim()
    const thumbnailUrl = body.thumbnailUrl != null && String(body.thumbnailUrl).trim() !== ''
        ? String(body.thumbnailUrl).trim()
        : null

    if (!content && !thumbnailUrl) {
        return NextResponse.json({ ok: false, error: 'CONTENT_REQUIRED' }, { status: 400 })
    }
    if (content.length > MAX_CONTENT_LENGTH) {
        return NextResponse.json({ ok: false, error: 'CONTENT_TOO_LONG' }, { status: 400 })
    }
    if (thumbnailUrl && !thumbnailUrl.startsWith('data:image/')) {
        return NextResponse.json({ ok: false, error: 'INVALID_THUMBNAIL' }, { status: 400 })
    }
    if (thumbnailUrl && thumbnailUrl.length > 7_000_000) {
        return NextResponse.json({ ok: false, error: 'THUMBNAIL_TOO_LARGE' }, { status: 400 })
    }

    const postId = globalThis.crypto?.randomUUID?.() ?? `bp_${Date.now()}_${Math.random().toString(16).slice(2)}`
    const createdAtSec = Math.floor(Date.now() / 1000)

    const { db, userId } = resolved

    await db.run(
        `INSERT INTO user_board_posts (post_id, user_id, content, thumbnail_url, is_pinned, created_at)
         VALUES (?, ?, ?, ?, 0, ?)`,
        [postId, userId, content, thumbnailUrl, createdAtSec]
    )

    const row = await db.get<{
        id: string
        displayName: string | null
        avatar: string | null
        content: string
        thumb: string | null
        created_at_sec: number
    }>(
        `SELECT 
            bp.post_id AS id,
            bp.content,
            bp.thumbnail_url AS thumb,
            bp.created_at AS created_at_sec,
            u.display_name AS displayName,
            u.avatar_url AS avatar
         FROM user_board_posts bp
         INNER JOIN users u ON bp.user_id = u.user_id
         WHERE bp.post_id = ?`,
        [postId]
    )

    if (!row) {
        return NextResponse.json({ ok: false, error: 'CREATE_FAILED' }, { status: 500 })
    }

    return NextResponse.json({
        ok: true,
        data: {
            post: {
                id: row.id,
                authorName: row.displayName ?? '',
                authorAvatar: row.avatar ?? '',
                date:
                    row.created_at_sec > 0
                        ? new Date(row.created_at_sec * 1000).toISOString().slice(0, 10)
                        : '',
                pinned: false,
                content: row.content,
                comments: 0,
                views: 0,
                thumb: row.thumb ?? '',
                thumbCount: row.thumb ? 1 : 0,
            },
        },
    })
}
