import { NextRequest, NextResponse } from 'next/server'
import { getDb } from '@/server/db'
import { validateSession } from '@/app/api/_helpers/session'

export const runtime = 'nodejs'

function json(data: unknown, init?: ResponseInit) {
    return NextResponse.json(data, init)
}

export async function POST(
    request: NextRequest,
    { params }: { params: { id: string; commentId: string } }
) {
    try {
        const catchId = String(params?.id ?? '').trim()
        const commentId = String(params?.commentId ?? '').trim()

        if (!catchId || !commentId) {
            return json({ ok: false, error: 'BAD_REQUEST' }, { status: 400 })
        }

        const userId = await validateSession(request)
        if (!userId) {
            return json({ ok: false, error: 'UNAUTHORIZED' }, { status: 401 })
        }

        const db = await getDb()

        const comment = await db.get<{ comment_id: string; catch_id: string }>(
            `SELECT comment_id, catch_id FROM catch_comments WHERE comment_id = ? AND catch_id = ?`,
            [commentId, catchId]
        )

        if (!comment) {
            return json({ ok: false, error: 'NOT_FOUND' }, { status: 404 })
        }

        const exists = await db.get<{ c: number }>(
            `SELECT 1 AS c FROM catch_comment_likes WHERE comment_id = ? AND user_id = ? LIMIT 1`,
            [commentId, userId]
        )

        let isLiked = false
        const nowSec = Math.floor(Date.now() / 1000)
        if (exists?.c) {
            await db.run(`DELETE FROM catch_comment_likes WHERE comment_id = ? AND user_id = ?`, [
                commentId,
                userId,
            ])
            isLiked = false
        } else {
            await db.run(
                `INSERT OR IGNORE INTO catch_comment_likes (comment_id, user_id, created_at) VALUES (?, ?, ?)`,
                [commentId, userId, nowSec]
            )
            isLiked = true
        }

        const c = await db.get<{ likes: number }>(
            `SELECT COUNT(1) AS likes FROM catch_comment_likes WHERE comment_id = ?`,
            [commentId]
        )
        const likes = Number(c?.likes ?? 0)

        return json({ ok: true, data: { commentId, isLiked, likes } })
    } catch (error: any) {
        console.error('Failed to toggle comment like:', error)
        return json(
            { ok: false, message: error?.message || 'Failed to toggle comment like' },
            { status: 500 }
        )
    }
}
